org.json和json-lib比較


經常會用到JSON格式才處理,尤其是在Http請求的時候,網上可以找到很多json處理的相關工具,如org.json和json-lib,下面兩段源代碼是分別使用這兩個工具解析和構造JSON的演示程序。  
//這是使用json-lib的程序:  
import JAVA.util.HashMap;  
import JAVA.util.Map;  
  
import net.sf.json.JSONObject;  
  
public class Test {  
  
    public static void main(String[] args) {  
        String json = "{\"name\":\"reiz\"}";  
        JSONObject jsonObj = JSONObject.fromObject(json);  
        String name = jsonObj.getString("name");  
        
        jsonObj.put("inITial", name.substring(0, 1).toUpperCASE());  
  
        String[] likes = new String[] { "JAVAScript", "Skiing", "Apple Pie" };  
        jsonObj.put("likes", likes);  
  
        Map <String, String> ingredients = new HashMap <String, String>();  
        ingredients.put("apples", "3kg");  
        ingredients.put("sugar", "1kg");  
        ingredients.put("pastry", "2.4kg");  
        ingredients.put("bestEaten", "outdoors");  
        jsonObj.put("ingredients",ingredients);  
        
        System.out.println(jsonObj);  
    }  
}  
//這是使用org.json的程序:  
import JAVA.util.HashMap;  
import JAVA.util.Map;  
  
import org.json.JSONException;  
import org.json.JSONObject;  
  
public class Test {  
  
    public static void main(String[] args) throws JSONException {  
        String json = "{\"name\":\"reiz\"}";  
        JSONObject jsonObj = new JSONObject(json);  
        String name = jsonObj.getString("name");  
  
        jsonObj.put("inITial", name.substring(0, 1).toUpperCASE());  
  
        String[] likes = new String[] { "JAVAScript", "Skiing", "Apple Pie" };  
        jsonObj.put("likes", likes);  
  
        Map <String, String> ingredients = new HashMap <String, String>();  
        ingredients.put("apples", "3kg");  
        ingredients.put("sugar", "1kg");  
        ingredients.put("pastry", "2.4kg");  
        ingredients.put("bestEaten", "outdoors");  
        jsonObj.put("ingredients", ingredients);  
        System.out.println(jsonObj);  
  
        System.out.println(jsonObj);  
    }  
}  
//兩者在生成json的時候幾乎是相同的,但org.json比json-lib要輕量得多,前者沒有任何依賴,而后者要依賴ezmorph和commons的lang、logging、beanutils、collections等組件。
但是往往使用的時候,我們會操作Bean和Json的轉換,org.json可以從Bean轉到json,似乎不能從json轉到Bean。下面是我找的幾個例子。
public class JsonUtil {         
        
            
    public static Object getObject4JsonString(String jsonString, Class pojoCalss) {         
        Object pojo;         
        JSONObject jsonObject = JSONObject.fromObject(jsonString);         
        pojo = JSONObject.toBean(jsonObject, pojoCalss);         
        return pojo;         
    }         
        
        
            
    public static Map getMap4Json(String jsonString) {         
        JSONObject jsonObject = JSONObject.fromObject(jsonString);         
        Iterator keyIter = jsonObject.keys();         
        String key;         
        Object value;         
        Map valueMap = new HashMap();         
        
        while (keyIter.hasNext()) {         
            key = (String) keyIter.next();         
            value = jsonObject.get(key);         
            valueMap.put(key, value);         
        }         
        
        return valueMap;         
    }         
        
        
            
    public static Object[] getObjectArray4Json(String jsonString) {         
        JSONArray jsonArray = JSONArray.fromObject(jsonString);         
        return jsonArray.toArray();         
        
    }         
        
        
            
    public static List getList4Json(String jsonString, Class pojoClass) {         
        
        JSONArray jsonArray = JSONArray.fromObject(jsonString);         
        JSONObject jsonObject;         
        Object pojoValue;         
        
        List list = new ArrayList();         
        for (int i = 0; i < jsonArray.size(); i++) {         
        
            jsonObject = jsonArray.getJSONObject(i);         
            pojoValue = JSONObject.toBean(jsonObject, pojoClass);         
            list.add(pojoValue);         
        
        }         
        return list;         
        
    }         
        
        
            
    public static String[] getStringArray4Json(String jsonString) {         
        
        JSONArray jsonArray = JSONArray.fromObject(jsonString);         
        String[] stringArray = new String[jsonArray.size()];         
        for (int i = 0; i < jsonArray.size(); i++) {         
            stringArray[i] = jsonArray.getString(i);         
        
        }         
        
        return stringArray;         
    }         
        
        
            
    public static Long[] getLongArray4Json(String jsonString) {         
        
        JSONArray jsonArray = JSONArray.fromObject(jsonString);         
        Long[] longArray = new Long[jsonArray.size()];         
        for (int i = 0; i < jsonArray.size(); i++) {         
            longArray[i] = jsonArray.getLong(i);         
        
        }         
        return longArray;         
    }         
        
        
            
    public static Integer[] getIntegerArray4Json(String jsonString) {         
        
        JSONArray jsonArray = JSONArray.fromObject(jsonString);         
        Integer[] integerArray = new Integer[jsonArray.size()];         
        for (int i = 0; i < jsonArray.size(); i++) {         
            integerArray[i] = jsonArray.getInt(i);         
        
        }         
        return integerArray;         
    }         
        
            
    public static Date[] getDateArray4Json(String jsonString, String DataFormat)         
            throws ParseException {         
        
        JSONArray jsonArray = JSONArray.fromObject(jsonString);         
        Date[] dateArray = new Date[jsonArray.size()];         
        String dateString;         
        Date date;         
        
        for (int i = 0; i < jsonArray.size(); i++) {         
            dateString = jsonArray.getString(i);         
            date = DateUtil.parseDate(dateString, DataFormat);         
            dateArray[i] = date;         
        
        }         
        return dateArray;         
    }         
        
        
            
    public static Double[] getDoubleArray4Json(String jsonString) {         
        
        JSONArray jsonArray = JSONArray.fromObject(jsonString);         
        Double[] doubleArray = new Double[jsonArray.size()];         
        for (int i = 0; i < jsonArray.size(); i++) {         
            doubleArray[i] = jsonArray.getDouble(i);         
        
        }         
        return doubleArray;         
    }         
        
        
            
    public static String getJsonString4JavaPOJO(Object javaObj) {         
        
        JSONObject json;         
        json = JSONObject.fromObject(javaObj);         
        return json.toString();         
        
    }         
        
            
    public static String getJsonString4JavaPOJO(Object javaObj,         
            String dataFormat) {         
        
        JSONObject json;         
        JsonConfig jsonConfig = configJson(dataFormat);         
        json = JSONObject.fromObject(javaObj, jsonConfig);         
        return json.toString();         
        
    }         
        
            
    public static JsonConfig configJson(String datePattern) {         
        JsonConfig jsonConfig = new JsonConfig();         
        jsonConfig.setExcludes(new String[] { "" });         
        jsonConfig.setIgnoreDefaultExcludes(false);         
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);         
        jsonConfig.registerJsonValueProcessor(Date.class,         
                new JsonDateValueProcessor(datePattern));         
        
        return jsonConfig;         
    }         
        
        
            
    public static JsonConfig configJson(String[] excludes, String datePattern) {         
        JsonConfig jsonConfig = new JsonConfig();         
        jsonConfig.setExcludes(excludes);         
        jsonConfig.setIgnoreDefaultExcludes(true);         
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);         
        jsonConfig.registerJsonValueProcessor(Date.class,         
                new JsonDateValueProcessor(datePattern));         
        
        return jsonConfig;         
    }         
        
}    
   
   
package com.baiyyy.polabs.util.json;         
        
import java.text.SimpleDateFormat;         
import java.util.Date;         
        
import net.sf.json.JsonConfig;         
import net.sf.json.processors.JsonValueProcessor;         
        
        
public class JsonDateValueProcessor implements JsonValueProcessor {            
               
    private String format = "yyyy-MM-dd HH:mm:ss";            
           
    public JsonDateValueProcessor() {            
           
    }            
           
    public JsonDateValueProcessor(String format) {            
        this.format = format;            
    }            
           
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {            
        String[] obj = {};            
        if (value instanceof Date[]) {            
            SimpleDateFormat sf = new SimpleDateFormat(format);            
            Date[] dates = (Date[]) value;            
            obj = new String[dates.length];            
            for (int i = 0; i < dates.length; i++) {            
                obj[i] = sf.format(dates[i]);            
            }            
        }            
        return obj;            
    }            
           
    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {            
        if (value instanceof Date) {            
            String str = new SimpleDateFormat(format).format((Date) value);            
            return str;            
        }            
        return value == null ? null : value.toString();            
    }            
           
    public String getFormat() {            
        return format;            
    }            
           
    public void setFormat(String format) {            
        this.format = format;            
    }            
           
}    
Json與javaBean之間的轉換工具類http://www.oschina.net/code/piece_full?code=17607
import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig;
/** * Json與javaBean之間的轉換工具類 * * @author 晚風工作室 www.soservers.com * @version 20111221 * * {@code 現使用json-lib組件實現 * 需要 * json-lib-2.4-jdk15.jar * ezmorph-1.0.6.jar * commons-collections-3.1.jar * commons-lang-2.0.jar * 支持 * } */ public class JsonPluginsUtil { /** * 從一個JSON 對象字符格式中得到一個java對象 * * @param jsonString * @param beanCalss * @return */ @SuppressWarnings("unchecked") public static <T> T jsonToBean(String jsonString, Class<T> beanCalss) { JSONObject jsonObject = JSONObject.fromObject(jsonString); T bean = (T) JSONObject.toBean(jsonObject, beanCalss); return bean; } /** * 將java對象轉換成json字符串 * * @param bean * @return */ public static String beanToJson(Object bean) { JSONObject json = JSONObject.fromObject(bean); return json.toString(); } /** * 將java對象轉換成json字符串 * * @param bean * @return */ public static String beanToJson(Object bean, String[] _nory_changes, boolean nory) { JSONObject json = null; if(nory){//轉換_nory_changes里的屬性 Field[] fields = bean.getClass().getDeclaredFields(); String str = ""; for(Field field : fields){ // System.out.println(field.getName()); str+=(":"+field.getName()); } fields = bean.getClass().getSuperclass().getDeclaredFields(); for(Field field : fields){ // System.out.println(field.getName()); str+=(":"+field.getName()); } str+=":"; for(String s : _nory_changes){ str = str.replace(":"+s+":", ":"); } json = JSONObject.fromObject(bean,configJson(str.split(":"))); }else{//轉換除了_nory_changes里的屬性 json = JSONObject.fromObject(bean,configJson(_nory_changes)); } return json.toString(); } private static JsonConfig configJson(String[] excludes) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes(excludes); // jsonConfig.setIgnoreDefaultExcludes(false); // // jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); // jsonConfig.registerJsonValueProcessor(Date.class, // // new DateJsonValueProcessor(datePattern)); return jsonConfig; } /** * 將java對象List集合轉換成json字符串 * @param beans * @return */ @SuppressWarnings("unchecked") public static String beanListToJson(List beans) { StringBuffer rest = new StringBuffer(); rest.append("["); int size = beans.size(); for (int i = 0; i < size; i++) { rest.append(beanToJson(beans.get(i))+((i<size-1)?",":"")); } rest.append("]"); return rest.toString(); } /** * * @param beans * @param _no_changes * @return */ @SuppressWarnings("unchecked") public static String beanListToJson(List beans, String[] _nory_changes, boolean nory) { StringBuffer rest = new StringBuffer(); rest.append("["); int size = beans.size(); for (int i = 0; i < size; i++) { try{ rest.append(beanToJson(beans.get(i),_nory_changes,nory)); if(i<size-1){ rest.append(","); } }catch(Exception e){ e.printStackTrace(); } } rest.append("]"); return rest.toString(); } /** * 從json HASH表達式中獲取一個map,改map支持嵌套功能 * * @param jsonString * @return */ @SuppressWarnings({ "unchecked" }) public static Map jsonToMap(String jsonString) { JSONObject jsonObject = JSONObject.fromObject(jsonString); Iterator keyIter = jsonObject.keys(); String key; Object value; Map valueMap = new HashMap(); while (keyIter.hasNext()) { key = (String) keyIter.next(); value = jsonObject.get(key).toString(); valueMap.put(key, value); } return valueMap; } /** * map集合轉換成json格式數據 * @param map * @return */ public static String mapToJson(Map<String, ?> map, String[] _nory_changes, boolean nory){ String s_json = "{"; Set<String> key = map.keySet(); for (Iterator<?> it = key.iterator(); it.hasNext();) { String s = (String) it.next(); if(map.get(s) == null){ }else if(map.get(s) instanceof List<?>){ s_json+=(s+":"+JsonPluginsUtil.beanListToJson((List<?>)map.get(s), _nory_changes, nory)); }else{ JSONObject json = JSONObject.fromObject(map); s_json += (s+":"+json.toString());; } if(it.hasNext()){ s_json+=","; } } s_json+="}"; return s_json; } /** * 從json數組中得到相應java數組 * * @param jsonString * @return */ public static Object[] jsonToObjectArray(String jsonString) { JSONArray jsonArray = JSONArray.fromObject(jsonString); return jsonArray.toArray(); } public static String listToJson(List<?> list) { JSONArray jsonArray = JSONArray.fromObject(list); return jsonArray.toString(); } /** * 從json對象集合表達式中得到一個java對象列表 * * @param jsonString * @param beanClass * @return */ @SuppressWarnings("unchecked") public static <T> List<T> jsonToBeanList(String jsonString, Class<T> beanClass) { JSONArray jsonArray = JSONArray.fromObject(jsonString); JSONObject jsonObject; T bean; int size = jsonArray.size(); List<T> list = new ArrayList<T>(size); for (int i = 0; i < size; i++) { jsonObject = jsonArray.getJSONObject(i); bean = (T) JSONObject.toBean(jsonObject, beanClass); list.add(bean); } return list; } /** * 從json數組中解析出java字符串數組 * * @param jsonString * @return */ public static String[] jsonToStringArray(String jsonString) { JSONArray jsonArray = JSONArray.fromObject(jsonString); String[] stringArray = new String[jsonArray.size()]; int size = jsonArray.size(); for (int i = 0; i < size; i++) { stringArray[i] = jsonArray.getString(i); } return stringArray; } /** * 從json數組中解析出javaLong型對象數組 * * @param jsonString * @return */ public static Long[] jsonToLongArray(String jsonString) { JSONArray jsonArray = JSONArray.fromObject(jsonString); int size = jsonArray.size(); Long[] longArray = new Long[size]; for (int i = 0; i < size; i++) { longArray[i] = jsonArray.getLong(i); } return longArray; } /** * 從json數組中解析出java Integer型對象數組 * * @param jsonString * @return */ public static Integer[] jsonToIntegerArray(String jsonString) { JSONArray jsonArray = JSONArray.fromObject(jsonString); int size = jsonArray.size(); Integer[] integerArray = new Integer[size]; for (int i = 0; i < size; i++) { integerArray[i] = jsonArray.getInt(i); } return integerArray; } /** * 從json數組中解析出java Double型對象數組 * * @param jsonString * @return */ public static Double[] jsonToDoubleArray(String jsonString) { JSONArray jsonArray = JSONArray.fromObject(jsonString); int size = jsonArray.size(); Double[] doubleArray = new Double[size]; for (int i = 0; i < size; i++) { doubleArray[i] = jsonArray.getDouble(i); } return doubleArray; } }

 

package com.mai.json;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.ezmorph.Morpher;
import net.sf.ezmorph.MorpherRegistry;
import net.sf.ezmorph.bean.BeanMorpher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import org.apache.commons.beanutils.PropertyUtils;
import org.junit.Test;

public class JsonLibTest {

    /*
     *  普通類型、List、Collection等都是用JSONArray解析
     *  
     *  Map、自定義類型是用JSONObject解析
     *  可以將Map理解成一個對象,里面的key/value對可以理解成對象的屬性/屬性值
     *  即{key1:value1,key2,value2......}
     * 
     * 1.JSONObject是一個name:values集合,通過它的get(key)方法取得的是key后對應的value部分(字符串)
     *         通過它的getJSONObject(key)可以取到一個JSONObject,--> 轉換成map,
     *         通過它的getJSONArray(key) 可以取到一個JSONArray ,
     * 
     * 
     */
    
    //一般數組轉換成JSON
    @Test
    public void testArrayToJSON(){
        boolean[] boolArray = new boolean[]{true,false,true};  
        JSONArray jsonArray = JSONArray.fromObject( boolArray );  
        System.out.println( jsonArray );  
        // prints [true,false,true]  
    }
    
    
    //Collection對象轉換成JSON
    @Test
    public void testListToJSON(){
        List list = new ArrayList();  
        list.add( "first" );  
        list.add( "second" );  
        JSONArray jsonArray = JSONArray.fromObject( list );  
        System.out.println( jsonArray );  
        // prints ["first","second"]  
    }
    
    
    //字符串json轉換成json, 根據情況是用JSONArray或JSONObject
    @Test
    public void testJsonStrToJSON(){
        JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );  
        System.out.println( jsonArray );  
        // prints ["json","is","easy"]  
    }
    
    
    //Map轉換成json, 是用jsonObject
    @Test
    public void testMapToJSON(){
        Map map = new HashMap();  
        map.put( "name", "json" );  
        map.put( "bool", Boolean.TRUE );  
        map.put( "int", new Integer(1) );  
        map.put( "arr", new String[]{"a","b"} );  
        map.put( "func", "function(i){ return this.arr[i]; }" );  
          
        JSONObject jsonObject = JSONObject.fromObject( map );  
        System.out.println( jsonObject );  
    }
    
    //復合類型bean轉成成json
    @Test
    public void testBeadToJSON(){
        MyBean bean = new MyBean();
        bean.setId("001");
        bean.setName("銀行卡");
        bean.setDate(new Date());
        
        List cardNum = new ArrayList();
        cardNum.add("農行");
        cardNum.add("工行");
        cardNum.add("建行");
        cardNum.add(new Person("test"));
        
        bean.setCardNum(cardNum);
        
        JSONObject jsonObject = JSONObject.fromObject(bean);
        System.out.println(jsonObject);
        
    }
    
    //普通類型的json轉換成對象
    @Test
    public void testJSONToObject() throws Exception{
        String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";  
        JSONObject jsonObject = JSONObject.fromObject( json ); 
        System.out.println(jsonObject);
        Object bean = JSONObject.toBean( jsonObject ); 
        assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) );  
        assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) );  
        assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) );  
        assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) );  
        assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) );  
        System.out.println(PropertyUtils.getProperty(bean, "name"));
        System.out.println(PropertyUtils.getProperty(bean, "bool"));
        System.out.println(PropertyUtils.getProperty(bean, "int"));
        System.out.println(PropertyUtils.getProperty(bean, "double"));
        System.out.println(PropertyUtils.getProperty(bean, "func"));
        System.out.println(PropertyUtils.getProperty(bean, "array"));
        
        List arrayList = (List)JSONArray.toCollection(jsonObject.getJSONArray("array"));
        for(Object object : arrayList){
            System.out.println(object);
        }
        
    }
    
    
    //將json解析成復合類型對象, 包含List
    @Test
    public void testJSONToBeanHavaList(){
        String json = "{list:[{name:'test1'},{name:'test2'}],map:{test1:{name:'test1'},test2:{name:'test2'}}}";
//        String json = "{list:[{name:'test1'},{name:'test2'}]}";
        Map classMap = new HashMap();
        classMap.put("list", Person.class);
        MyBeanWithPerson diyBean = (MyBeanWithPerson)JSONObject.toBean(JSONObject.fromObject(json),MyBeanWithPerson.class , classMap);
        System.out.println(diyBean);
        
        List list = diyBean.getList();
        for(Object o : list){
            if(o instanceof Person){
                Person p = (Person)o;
                System.out.println(p.getName());
            }
        }
    }
    
    
    //將json解析成復合類型對象, 包含Map
    @Test
    public void testJSONToBeanHavaMap(){
        //把Map看成一個對象
        String json = "{list:[{name:'test1'},{name:'test2'}],map:{testOne:{name:'test1'},testTwo:{name:'test2'}}}";
        Map classMap = new HashMap();
        classMap.put("list", Person.class);
        classMap.put("map", Map.class);
        //使用暗示,直接將json解析為指定自定義對象,其中List完全解析,Map沒有完全解析
        MyBeanWithPerson diyBean = (MyBeanWithPerson)JSONObject.toBean(JSONObject.fromObject(json),MyBeanWithPerson.class , classMap);
        System.out.println(diyBean);
        
        System.out.println("do the list release");
        List<Person> list = diyBean.getList();
        for(Person o : list){
            Person p = (Person)o;
            System.out.println(p.getName());
        }
        
        System.out.println("do the map release");
        
        //先往注冊器中注冊變換器,需要用到ezmorph包中的類
        MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();
        Morpher dynaMorpher = new BeanMorpher( Person.class,  morpherRegistry);  
        morpherRegistry.registerMorpher( dynaMorpher );  
        
        
        Map map = diyBean.getMap();
        /*這里的map沒進行類型暗示,故按默認的,里面存的為net.sf.ezmorph.bean.MorphDynaBean類型的對象*/
        System.out.println(map);
      /*輸出:
        {testOne=net.sf.ezmorph.bean.MorphDynaBean@f73c1[
          {name=test1}
        ], testTwo=net.sf.ezmorph.bean.MorphDynaBean@186c6b2[
          {name=test2}
        ]}
      */
        List<Person> output = new ArrayList();  
        for( Iterator i = map.values().iterator(); i.hasNext(); ){  
            //使用注冊器對指定DynaBean進行對象變換
           output.add( (Person)morpherRegistry.morph( Person.class, i.next() ) );  
        }  
        
        for(Person p : output){
            System.out.println(p.getName());
        /*輸出:
          test1
          test2
        */
        }
        
    }
    
    
    
}
 
http://www.cnblogs.com/mailingfeng/archive/2012/01/18/2325707.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM