日期:2014-05-16  浏览次数:20500 次

java与json互相转换(解决日期和去除属性问题)
JSON 即 JavaScript Object Natation,它是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互。本文主要讲解下java和JSON之间的转换,特别是解决互相转换遇到日期问题和指定属性的过滤。
    一、需要相关的jar包:
     json-lib-xxx.jar
    ezmorph-xxx.jar
    commons-httpclient-xxx.jar
    commons-lang-xxx.jar
    commons-logging-xxx.jar
    commons-collections-xxx.jar
    上面的包可以从下面的连接下载:
    http://commons.apache.org/index.html
    http://json-lib.sourceforge.net
    http://ezmorph.sourceforge.net
   二、java-》JSON
     1.List-》JSON
Java代码 
List<String> list = new ArrayList<String>(); 
        list.add("apple"); 
        list.add("orange"); 
        JSONArray jarr = JSONArray.fromObject(list); 
        System.out.println("list->json:" + jarr.toString()); 

    打印结果:list->json:["apple","orange"]
     2.Map-》JSON
Java代码 
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()); 

    打印结果:map->json:{"age":30,"name":"Michael","baby":["Lucy","Lily"]}
    3.bean->JSON
Java代码 
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()); 

   打印结果: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"}
    4.bean->JSON 日期转换
   上面的例子中你会发现它把bean对象里的util.Date这个类型的所有属性一一转换出来。在实际运用过程中,大多数情况下我们希望能转化为yyyy-MM-dd这种格式,下面就讲一讲如何实现:
   首先要写一个新的类JsonDateValueProcessor如下:
Java代码 
/**
* JSON 日期格式处理(java转化为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;