java and json interchangeable (settlement date of issue)

sponsored links
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]
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of java and json interchangeable (settlement date of issue)

  • Build flex + spring + blazeds + hibernate application

    Build flex + spring + blazeds + hibernate application First, set up the project blazeds 1, will blazeds.war extract to a directory, such as: myflex /; 2, set up java works were such as: MyFlex, in the orientation of selection create project from exis ...

  • Hibernate connection pool configuration

    Hibernate connection pool configuration <! - Jdbc -> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </ property> <property name="connection.url"> jdbc: oracle: thin: @ 10.203.14.132:15

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • First Hibernate Example

    Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co

  • Spring2.0 + hibernate3.1 + log4j + mysql demo

    applicationContext.xml Non-attachment jar package, necessary friends can send an email to todd.liangt @ gmail.com

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

  • Hibernate's lazy strategy

    hibernate Lazy strategy can be used in: <class> tag, it can be true / false Tags can <PROPERTY> values true / false type of necessary tools to enhance <set> <list> can tag values true / false / extra <many-to-one> <on ...

  • spring struts2.0 hibernate bug killer 1

    exception There is no Action mapped for namespace / and action name checkLogin. - [Unknown location] com.opensymphony.xwork2.DefaultActionProxy.prepare (DefaultActionProxy.java: 186) org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries