java and json interchangeable (settlement date of issue)

JSON or JavaScript Object Natation, it is a lightweight data interchange format, is ideal for server and JavaScript interaction. In this paper, to explain under the conversion between java and JSON, in particular, to address each question of the date of conversion experience.
One needs the relevant jar package:
json-lib-xxx.jar
ezmorph-xxx.jar
commons-httpclient-xxx.jar
commons-lang-xxx.jar
commons-logging-xxx.jar
commons-collections-xxx.jar
The above packages can be downloaded from the following link:
http://commons.apache.org/index.html
http://json-lib.sourceforge.net
http://ezmorph.sourceforge.net
2, java-"JSON
1.List-"JSON

List<String> list = new ArrayList<String>();
        list.add("apple");
        list.add("orange");
        JSONArray jarr = JSONArray.fromObject(list);
        System.out.println("list->json:" + jarr.toString());

Print Results: list-> json: [ "apple", "orange"]
2.Map-"JSON

Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "Michael");
        map.put("baby", new String[] { "Lucy", "Lily" });
        map.put("age", 30);
        JSONObject jo = JSONObject.fromObject(map);
        System.out.println("map->json:" + jo.toString());

Print Results: map-> json: ( "age": 30, "name": "Michael", "baby": [ "Lucy", "Lily"])
3.bean-> JSON

JsonBean bean = new JsonBean();
        bean.setName("NewBaby");
        bean.setAge(1);
        bean.setBorn(new Date());
        jo = JSONObject.fromObject(bean);
        System.out.println("bean->json:" + jo.toString());

Print Results: bean-> json: ( "age": 1, "born": ( "date": 10, "day": 3, "hours": 14, "minutes": 14, "month": 2, "seconds": 1, "time": 1268201641228, "timezoneOffset": -480, "year": 110), "name": "NewBaby")
Then you will find it inside the bean object util.Date all of the attributes of this type of conversion out of 11. In actual application process, in most cases we hope to translate into yyyy-MM-dd format, Here's to talk about how to achieve:
First, write a new class JsonDateValueProcessor are as follows:

/**
 * JSON  Date formats to handle  (java Into  JSON)
 * @author Michael sun
 */
public class JsonDateValueProcessor implements JsonValueProcessor {

    /**
     * datePattern
     */
    private String datePattern = "yyyy-MM-dd";

    /**
     * JsonDateValueProcessor
     */
    public JsonDateValueProcessor() {
        super();
    }

    /**
     * @param format
     */
    public JsonDateValueProcessor(String format) {
        super();
        this.datePattern = format;
    }

    /**
     * @param value
     * @param jsonConfig
     * @return Object
     */
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return process(value);
    }

    /**
     * @param key
     * @param value
     * @param jsonConfig
     * @return Object
     */
    public Object processObjectValue(String key, Object value,
            JsonConfig jsonConfig) {
        return process(value);
    }

    /**
     * process
     * @param value
     * @return
     */
    private Object process(Object value) {
        try {
            if (value instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat(datePattern,
                        Locale.UK);
                return sdf.format((Date) value);
            }
            return value == null ? "" : value.toString();
        } catch (Exception e) {
            return "";
        }

    }

    /**
     * @return the datePattern
     */
    public String getDatePattern() {
        return datePattern;
    }

    /**
     * @param pDatePattern the datePattern to set
     */
    public void setDatePattern(String pDatePattern) {
        datePattern = pDatePattern;
    }

}

Test Code:

JsonBean bean = new JsonBean();
        bean.setName("NewBaby");
        bean.setAge(1);
        bean.setBorn(new Date());

        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class,
                new JsonDateValueProcessor());

        JSONObject jo = JSONObject.fromObject(bean, jsonConfig);
        System.out.println("bean->json:" + jo.toString());

Print Results: bean-> json: ( "age": 1, "born": "2010-03-10", "name": "NewBaby")
It can get what we want result.

3, JSON-"java
1. How to json in yyyy-MM-dd conversion of the Bean in the util.Date type:

JSONUtils.getMorpherRegistry().registerMorpher(
                new DateMorpher(new String[] { "yyyy-MM-dd" }));

        String jsonStr = "[{\"name\": \"husband\", \"age\": \"26\", \"born\": \"1984-01-12\"},{\"name\": \"wife\", \"age\": \"20\", \"born\": \"1990-05-01\"}]";

        Collection<JsonBean> list = JSONArray.toCollection(JSONArray
                .fromObject(jsonStr), JsonBean.class);
      //DateUtil.getFormatDate(date,fmtstr) Date change string here no longer write code
        for (JsonBean o : list) {
            System.out.println(DateUtil
                    .getFormatDate(o.getBorn(), "yyyy-MM-dd"));
        }

Print Results:
1984-01-12
1990-05-01
2. JSON-"List, Map

String listStr = "[\"apple\",\"orange\"]";
        Collection<String> strlist = JSONArray.toCollection(JSONArray
                .fromObject(listStr));
        for (String str : strlist) {
            System.out.println(str);
        }

        String mapStr = "{\"age\":30,\"name\":\"Michael\",\"baby\":[\"Lucy\",\"Lily\"]}";
        Map<String, Object> map = (Map) JSONObject.toBean(JSONObject
                .fromObject(mapStr), Map.class);
        for (Entry<String, Object> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "  " + entry.getValue());
        }

Print Results:
apple
orange
name Michael
age 30
baby [Lucy, Lily]

分类:Java 时间:2009-08-31 人气:317
分享到:
blog comments powered by Disqus

相关文章

  • SQL Server datetime format conversion date used 2010-12-20

    We often need to use a variety of for some purposes the date format, of course, we can use string manipulation to construct a variety of date formats, but there are ready-made function why not? SQL Server Chinese version of the default date field is

  • sql server date format conversion method Daquan ---- reproduced 2010-09-08

    sql server date format conversion method Daquan Sql server database in operation, it often will use the date format conversion method, I compiled a frequently used inside SQL Server date format conversion of several methods for later use. Chinese ver

  • Date of query SQL Server date format conversion 2011-02-18

    Date of query SQL Server date format conversion Issues: Often have such a query request, input or produce the calendar control date format yyyy-mm-dd, and database fields are datetime type, that is yyyy-mm-dd hh: mm: ss. If you use between a simple s

  • [SQLServer] date format conversion 2011-06-13

    --SQLSERVER Date format conversion SELECT CONVERT(VARCHAR(20), GETDATE(), 120 ) --2011-06-13 13:54:18 SELECT CONVERT(VARCHAR(10),GETDATE(),120) --2011-06-13 SELECT CONVERT(VARCHAR(12) , GETDATE(), 111 ) --2011/06/13 SELECT CONVERT(VARCHAR(12) , GETDA

  • ext/date/php_date.lo is not a valid libtool object 2013-10-29

    今天在安装php-5.3.10时,make报错: ext/date/php_date.lo is not a valid libtool object。 查看libtool(由ltmain.sh生成)该错误是由于: if (${SED} -e ’2q’ $arg | grep “^# Generated by .*$PACKAGE”) >/dev/null 2>&1; then 语句不成立而后续引起的。 正确的lo文件应该如下: # ext/date/php_date.lo

  • Oracle data types and storage methods (c) the date and time types 2010-08-26

    The third part of the date time type § 3.1 DATE Date Type Oralce used to represent the date and time data types. Fixed occupy 7 bytes. Including the seven attributes: Century century year month day hour minute and second of the month SQL> create t

  • Struts2 Data Tags (e) the use of s: date tag and format the date output 2011-01-05

    1.s: date overview of the label s: date tag feature is for date and time, and time with formatting functions. s: date tag attributes and significance of Property name If necessary Type Help format false String Formatted date string name true String D

  • util.date before the conversion with the sql.date 2008-09-22

    I was doing an inser operation time to obtain the current time into the database directly ps.setDate (new java.util.Date ()); However, conversion errors will be reported At this point should be ps.setDate (sqlDate); Can the

  • oracle date format conversion 2010-05-07

    Sqlplus or sqlplusw in default under or programming process, execute the command, if a session is sure the same will produce the effect you want. If you want a whole database level get rid of need to modify the parameters of the default format file, ...

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.247 (s). 14 q(s)