Java JSON总结

常用JSON:Apache JSON、FastJSON、Jackson、Google Gson

1  JSONObject put,accumulate,element的区别  

public Object put (Object key, Object value) 将value映射到key下。如果此JSONObject对象之前存在一个value在这个key下,当前的value会替换掉之前的value

Associates the specified value with the specified key in this map(optional operation). If the map previously contained . a mapping for this key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true .))

public JSONObject accumulate (String key, Object value) 累积value到这个key下。这个方法同element()方法类似,特殊的是,如果当前已经存在一个value在这个key下那么一个JSONArray将会存储在这个key下来保存所有累积的value。如果已经存在一个JSONArray,那么当前的value就会添加到这个JSONArray中

。相比之下replace方法会替代先前的value

Accumulate values under a key. It is similar to the element method except that if there is already an object stored 

under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a 

JSONArray, then the new value is appended to it. In contrast, the replace method replaces the previous value.

public JSONObject element (String key, Object value) 将键/值对放到这个JSONObject对象里面。如果当前value为空(null),那么如果这个key存在的话,这个key就会移除掉。如果这

个key之前有value值,那么此方法会调用accumulate()方法。

Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if it is 

present. If there is a previous value assigned to the key, it will call accumulate.

2

java json解析类库 Jackson 基础

Jackson是一个高效的java bean 到json的转换工具,项目主页http://jackson.codehaus.org/


Jackson提供了三种处理Json的方法,分别是:
Streaming API :基于独立事件模型处理JSON。效率最高,是下面两种方式的基础。
分别用org.codehaus.jackson.JsonParser 和 org.codehaus.jackson.JsonGenerator 读写Json

Tree Model :基于一个可变的树表示一个Json模型。最灵活
org.codehaus.jackson.map.ObjectMapper 创建树(基于JsonNode为节点)
Tree Model与XML DOM类似

 

Data Binding:用属性存取或者注释来处理从Json到POJO的转换。最方便,常用这种API
有简单绑定和全数据绑定,同样用org.codehaus.jackson.map.ObjectMapper处理

 

下面是Data Binding方法的基本使用
首先是将java bean转换为JSON

复制代码
 1 public static void main(String[] args) {  
 2     TestGridBean bean=null;  
 3     Vector vec = new Vector();  
 4     for(int i=0;i<1000;i++) {  
 5         bean = new TestGridBean();  
 6         bean.setNo(i);  
 7         bean.setName("姓名"+i);  
 8         bean.setMathscore(i);  
 9         bean.setEnscore(i);  
10         vec.add(bean);  
11     }  
12     //ObjectMapper 线程安全具有缓存机制,重用可显著提高效率,实际使用中可设为全局公用  
13     ObjectMapper mapper = new ObjectMapper();  
14     //用此类构造字符串  
15     StringWriter w=new StringWriter();  
16     try {  
17         //writeXXX方法是将对象写成JSON,readXXX方法是将JSON封装成对象  
18         mapper.writeValue(w, vec);  
19     } catch (JsonGenerationException e) {  
20         e.printStackTrace();  
21     } catch (JsonMappingException e) {  
22         e.printStackTrace();  
23     } catch (IOException e) {  
24         e.printStackTrace();  
25     }  
26     String s = w.toString();  
27     S.echo(s);  
28 }  
复制代码



然后是JSon到java bean 的转换

用GT-Grid前台传入的表格参数json为例,其格式为形如:

复制代码
{"recordType":"object",   "pageInfo":{"pageSize":20,"pageNum":1,"totalRowNum":-1,"totalPageNum":0,"startRowNum":1,"endRowNum":-1},  
"columnInfo":[  
    {"id":"no","header":"学号","fieldName":"no","fieldIndex":"no","sortOrder":null,"hidden":false,"exportable":true,"printable":true},  
    {"id":"name","header":"姓名","fieldName":"name","fieldIndex":"name","sortOrder":null,"hidden":false,"exportable":true,"printable":true},  
    {"id":"total","header":"总成绩","fieldName":"total","fieldIndex":"total","sortOrder":null,"hidden":false,"exportable":true,"printable":true},  
    {"id":"detail","header":"详细信息","fieldName":"detail","fieldIndex":"detail","sortOrder":null,"hidden":false,"exportable":true,"printable":true}  
   ],  
"sortInfo":[],  
"filterInfo":[],  
"remotePaging":true,  
"parameters":{},  
 "action":"load"}  
复制代码

以上json对应的java bean应该是如下格式:

复制代码
package gxlu.ims.webapps.action.syncResultQuery;  
import java.io.Serializable;  
public class GTGridBean implements Serializable {  
    /** 
     *  
     */  
    private static final long serialVersionUID = 1L;  
    private String recordType;  
    private String[] sortInfo;  
    private String[] filterInfo;  
    private boolean remotePaging;  
    private String action;  
    private PageInfo pageInfo;  
    private ColumnInfo[] columnInfo;  
    private Parameters parameters;  
      
    public static class PageInfo {  
        private String pageSize;  
        private long pageNum;  
        private long totalPageNum;  
        private long totalRowNum;  
        private long startRowNum;  
        private long endRowNum;  
        public String getPageSize() {  
            return pageSize;  
        }  
        public void setPageSize(String pageSize) {  
            this.pageSize = pageSize;  
        }  
        public long getPageNum() {  
            return pageNum;  
        }  
        public void setPageNum(long pageNum) {  
            this.pageNum = pageNum;  
        }  
        public long getTotalRowNum() {  
            return totalRowNum;  
        }  
        public void setTotalRowNum(long totalRowNum) {  
            this.totalRowNum = totalRowNum;  
        }  
        public long getStartRowNum() {  
            return startRowNum;  
        }  
        public void setStartRowNum(long startRowNum) {  
            this.startRowNum = startRowNum;  
        }  
        public long getEndRowNum() {  
            return endRowNum;  
        }  
        public void setEndRowNum(long endRowNum) {  
            this.endRowNum = endRowNum;  
        }  
        public long getTotalPageNum() {  
            return totalPageNum;  
        }  
        public void setTotalPageNum(long totalPageNum) {  
            this.totalPageNum = totalPageNum;  
        }  
    }  
      
    public static class ColumnInfo {  
        private String  id;  
        private String header;  
        private String fieldName;  
        private String fieldIndex;  
        private String sortOrder;  
        private boolean hidden;  
        private boolean exportable;  
        private boolean printable;  
        public String getId() {  
            return id;  
        }  
        public void setId(String id) {  
            this.id = id;  
        }  
        public String getHeader() {  
            return header;  
        }  
        public void setHeader(String header) {  
            this.header = header;  
        }  
        public String getFieldName() {  
            return fieldName;  
        }  
        public void setFieldName(String fieldName) {  
            this.fieldName = fieldName;  
        }  
        public String getFieldIndex() {  
            return fieldIndex;  
        }  
        public void setFieldIndex(String fieldIndex) {  
            this.fieldIndex = fieldIndex;  
        }  
        public String getSortOrder() {  
            return sortOrder;  
        }  
        public void setSortOrder(String sortOrder) {  
            this.sortOrder = sortOrder;  
        }  
        public boolean isHidden() {  
            return hidden;  
        }  
        public void setHidden(boolean hidden) {  
            this.hidden = hidden;  
        }  
        public boolean isExportable() {  
            return exportable;  
        }  
        public void setExportable(boolean exportable) {  
            this.exportable = exportable;  
        }  
        public boolean isPrintable() {  
            return printable;  
        }  
        public void setPrintable(boolean printable) {  
            this.printable = printable;  
        }  
    }  
      
    public static class Parameters {  
          
    }  
      
    public String getRecordType() {  
        return recordType;  
    }  
    public void setRecordType(String recordType) {  
        this.recordType = recordType;  
    }  
    public PageInfo getPageInfo() {  
        return pageInfo;  
    }  
    public void setPageInfo(PageInfo pageInfo) {  
        this.pageInfo = pageInfo;  
    }  
    public String[] getSortInfo() {  
        return sortInfo;  
    }  
    public void setSortInfo(String[] sortInfo) {  
        this.sortInfo = sortInfo;  
    }  
    public String[] getFilterInfo() {  
        return filterInfo;  
    }  
    public void setFilterInfo(String[] filterInfo) {  
        this.filterInfo = filterInfo;  
    }  
    public boolean isRemotePaging() {  
        return remotePaging;  
    }  
    public void setRemotePaging(boolean remotePaging) {  
        this.remotePaging = remotePaging;  
    }  
    public String getAction() {  
        return action;  
    }  
    public void setAction(String action) {  
        this.action = action;  
    }  
      
    public static long getSerialversionuid() {  
        return serialVersionUID;  
    }  
    public Parameters getParameters() {  
        return parameters;  
    }  
    public void setParameters(Parameters parameters) {  
        this.parameters = parameters;  
    }  
    public ColumnInfo[] getColumnInfo() {  
        return columnInfo;  
    }  
    public void setColumnInfo(ColumnInfo[] columnInfo) {  
        this.columnInfo = columnInfo;  
    }  
}  
复制代码

使用jsckson转换的代码:

复制代码
1 public void testPageData() throws Exception {  
2     String json = req.getParameter("_gt_json");  
3     S.echo(json);  
4     //将json转换为java bean用readXXX方法  
5     Object obj = mapper.readValue(json, GTGridBean.class);  
6     S.echo(obj);  
7 }
复制代码

 

Google Gson应用

1 .需要的Jar包
 
     1 ) Google Gson(gson-xxx.jar)下载地址:http: //code.google.com/p/google-gson/downloads/list
 
     2 )JUnit4
 
2 . 应用实例代码
 
     下载地址:http: //download.csdn.net/source/3499627
 
包括如下类:
 
1 )普通JavaBean类/带日期属性的JavaBean类:JavaBean.java/DateBean.java
 
2 )日期序列/反序列工具类:DateSerializerUtils.java、DateDeserializerUtils.java
 
3 )测试类GsonTester.java
 
具体代码:
 
1 )JavaBean类/DateBean类
 
      JavaBean属性:String id、String name、 int  age、String addr;
 
      DateBean属性:String id、String name、 int  age、java.util.Date date;
 
2
 
DateSerializerUtils.java
 
package  com.lupeng.javase.json.util;
 
  
 
import  java.lang.reflect.Type;
 
import  java.util.Date;
 
import  com.google.gson.JsonElement;
 
import  com.google.gson.JsonPrimitive;
 
import  com.google.gson.JsonSerializationContext;
 
import  com.google.gson.JsonSerializer;
 
  
 
/**
 
  * 日期解序列实用工具类
 
  * @author Lupeng
 
  * @date   2011-08-06
 
  */
 
public  class  DateSerializerUtils implements  JsonSerializer<java.util.Date>{
 
     @Override
 
     public  JsonElement serialize(Date date, Type type,
 
            JsonSerializationContext content) {
 
        return  new  JsonPrimitive(date.getTime());
 
     }
 
  
 
}
 
DateDeserializerUtils.java
 
package  com.lupeng.javase.json.util;
 
  
 
import  java.lang.reflect.Type;
 
import  com.google.gson.JsonDeserializationContext;
 
import  com.google.gson.JsonDeserializer;
 
import  com.google.gson.JsonElement;
 
import  com.google.gson.JsonParseException;
 
/**
 
  * 日期序列化实用工具类
 
  * @author Lupeng
 
  * @date   2011-08-06
 
  */
 
public  class  DateDeserializerUtils implements  JsonDeserializer<java.util.Date>{
 
     @Override
 
     public  java.util.Date deserialize(JsonElement json, Type type,
 
            JsonDeserializationContext context) throws  JsonParseException {
 
        return  new  java.util.Date(json.getAsJsonPrimitive().getAsLong());
 
     }
 
  
 
}
 
  
 
3 )测试类GsonTester.java
 
package  com.lupeng.javase.apps.json;
 
  
 
import  java.text.DateFormat;
 
import  java.util.ArrayList;
 
import  java.util.Date;
 
import  java.util.HashMap;
 
import  java.util.List;
 
import  java.util.Map;
 
  
 
import  org.junit.Before;
 
import  org.junit.Test;
 
  
 
import  com.google.gson.Gson;
 
import  com.google.gson.GsonBuilder;
 
import  com.lupeng.javase.json.bean.DateBean;
 
import  com.lupeng.javase.json.bean.JavaBean;
 
import  com.lupeng.javase.json.util.DateDeserializerUtils;
 
import  com.lupeng.javase.json.util.DateSerializerUtils;
 
  
 
/**
 
  * Google Gson解析Json数据实例
 
  *
 
  * 1.Bean、Json转换          testBeanJson()
 
  * 2.List -> Json转换     testList2Json()
 
  * 3.泛型List、Json相互转换 testGenericList2Json()
 
  * 4.Map -> Json转换         testMap2Json()
 
  * 5.泛型Map、Json相互转换 testGenericMap2Json()
 
  * 6.带日期属性Bean、Json转换  testDateBeanJson()
 
  * 7.带日期属性泛型List、Json转换
 
  *                           testDateGenericListJson()
 
  *
 
  * @author Lupeng
 
  * @create 2011-08-05
 
  * @modify 2011-08-06
 
  */
 
@SuppressWarnings ( "unchecked" )
 
public  class  GsonTester {
 
     private  Gson gson = null ;
 
     private  GsonBuilder gsonBuilder = null ;
 
    
 
     @Before
 
     public  void  setUp() {
 
        gson = new  Gson();
 
        gsonBuilder = new  GsonBuilder();
 
     }
 
     /**
 
      * JavaBean、Json相互转换
 
      */
 
     @Test
 
     public  void  testBeanJson() {
 
        JavaBean bean = new  JavaBean( "1001" , "scott" , 20 , "TL" );
 
       
 
        // Bean -> Json
 
        String json = gson.toJson(bean);
 
        System.out.println(json);
 
       
 
        // Json -> Bean
 
        bean = gson.fromJson(json, JavaBean. class );
 
        System.out.println(bean);
 
     }
 
    
 
     /**
 
      * List转换成Json字符串
 
      */
 
     @Test
 
     public  void  testList2Json() {
 
        // List
 
        List list = new  ArrayList();
 
        for ( int  i = 0 ; i < 5 ; i++) {
 
            list.add( "element"  + i);
 
        }
 
        System.out.println(list);
 
       
 
        // List -> Json
 
        String json = gson.toJson(list);
 
        System.out.println(json);
 
     }
 
    
 
     /**
 
      * 泛型List、Json相互转换
 
      */
 
     @Test
 
     public  void  testGenericListJson() {
 
        // 泛型List
 
        List<JavaBean> list = new  ArrayList<JavaBean>();
 
        for ( int  i = 0 ; i < 3 ; i++) {
 
            JavaBean user = new  JavaBean( "100"  + i, "name"  + i, 20  + i, "BJ"  + i);
 
            list.add(user);
 
        }
 
        System.out.println(list);
 
       
 
        // 泛型List -> Json
 
        java.lang.reflect.Type type =
 
            new  com.google.gson.reflect.TypeToken<List<JavaBean>>(){}.getType();
 
        String json = gson.toJson(list, type);
 
        System.out.println(json); 
 
       
 
        // Json -> 泛型List
 
        List<JavaBean> users = gson.fromJson(json.toString(), type);
 
        System.out.println(users);
 
     }
 
    
 
     /**
 
      * Map转换成Json字符串
 
      */
 
     @Test
 
     public  void  testMap2Json() {
 
        // Map数据
 
        Map map = new  HashMap();
 
        map.put( "id" , "1001" );
 
        map.put( "name" , "scott" );
 
        map.put( "age" , 20 );
 
        map.put( "addr" , "BJ" );
 
        System.out.println(map);
 
       
 
        // Map -> Json
 
        String json = gson.toJson(map);
 
        System.out.println(json);
 
     }
 
    
 
     /**
 
      * 泛型Map、Json相互转换
 
      */
 
     @Test
 
     public  void  testGenericMapJson() {
 
        // 泛型Map数据
 
        Map<String, JavaBean> map = new  HashMap<String, JavaBean>();
 
        for ( int  i = 0 ; i < 5 ; i++) {
 
            JavaBean user = new  JavaBean( "100"  + i, "name"  + i, 20  + i, "LN"  + i);
 
            map.put( "100"  + i, user);
 
        }
 
        System.out.println(map);
 
       
 
        // 泛型Map -> Json
 
        java.lang.reflect.Type type =
 
            new  com.google.gson.reflect.TypeToken<Map<String, JavaBean>>(){}.getType();
 
        String json = gson.toJson(map, type);
 
        System.out.println(json); 
 
       
 
        // Json -> Map
 
        Map<String, JavaBean> users = gson.fromJson(json.toString(), type);
 
        System.out.println(users);
 
       
 
     }
 
    
 
     /**
 
      * 带日期类型Bean、Json相互转换
 
      */
 
     @Test
 
     public  void  testDateBeanJson() {
 
        // 日期Bean数据
 
        DateBean bean = new  DateBean( "1001" , "scott" , 20 , new  Date());
 
       
 
        // Bean(带日期属性) -> Json
 
        gson = gsonBuilder.registerTypeAdapter(java.util.Date. class ,
 
               new  DateSerializerUtils()).setDateFormat(DateFormat.LONG).create();
 
        String json = gson.toJson(bean);
 
        System.out.println(json);
 
       
 
        // Json -> Bean(带日期类型属性)
 
        gson = gsonBuilder.registerTypeAdapter(java.util.Date. class ,
 
               new  DateDeserializerUtils()).setDateFormat(DateFormat.LONG).create();
 
        java.lang.reflect.Type type =
 
            new  com.google.gson.reflect.TypeToken<DateBean>(){}.getType();
 
        DateBean b = gson.fromJson(json, type);
 
        System.out.println(b);
 
     }
 
     /**
 
      * 泛型日期List、Json相互转换
 
      */
 
     @Test
 
     public  void  testDateGenericListJson() {
 
        // 泛型日期List
 
        List<DateBean> list = new  ArrayList<DateBean>();
 
        for ( int  i = 0 ; i < 3 ; i++) {
 
            DateBean user = new  DateBean( "100"  + i, "name"  + i, 20  + i, new  Date());
 
            list.add(user);
 
        }
 
        System.out.println(list);
 
       
 
        // 泛型日期List -> Json
 
        gson = gsonBuilder.registerTypeAdapter(java.util.Date. class ,
 
               new  DateSerializerUtils()).setDateFormat(DateFormat.LONG).create();
 
        java.lang.reflect.Type type =
 
            new  com.google.gson.reflect.TypeToken<List<DateBean>>(){}.getType();
 
        String json = gson.toJson(list, type);
 
        System.out.println(json); 
 
       
 
        // Json -> 泛型日期List
 
        gson = gsonBuilder.registerTypeAdapter(java.util.Date. class ,
 
               new  DateDeserializerUtils()).setDateFormat(DateFormat.LONG).create();
 
        List<DateBean> users = gson.fromJson(json.toString(), type);
 
        System.out.println(users);
 
     }
 
}

猜你喜欢

转载自aoyouzi.iteye.com/blog/2283757