org.json和json-lib比较

时间:2024-04-12 10:34:36
经常会用到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 = ; i < size; i++) { rest.append(beanToJson(beans.get(i))+((i<size-)?",":"")); } 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 = ; i < size; i++) {
try{
rest.append(beanToJson(beans.get(i),_nory_changes,nory));
if(i<size-){
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 = ; 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 = ; 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 = ; 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 = ; 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 = ; 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() );
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("");
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