当前位置: 首页 > 工具软件 > JSON lib > 使用案例 >

JSON解析类库之JSON-lib --- JSON-lib类库学习, 生成与解析json数据, json字符串与Java对象互转

谭梓
2023-12-01

JSON解析类库之JSON-lib --- JSON-lib类库学习, 生成与解析json数据, json字符串与Java对象互转


前言

JSON-lib是java项目开发中,经常用到的json数据解析与生成的Java类库,历史比较悠久。不过已经N年没有更新了,且性能效率实在是很一般,在互联网项目中是坚决不建议使用这个类库的。该类库依赖的jar包就有5个。但是经常在一些老项目维护中看到JSON-lib的使用。


一、什么是 JSON

JSON(JavaScript Object Notation)(官网网站:http://www.json.org/)是 一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。它基于 JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999 的一个子集。 JSON 采用完全独立于语言的文本格式,但是也使用了类似于 C 语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使 JSON 成为理想的数据交换语言。


二、JSON 的两种结构
1、“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表 (hash table),有键列表(keyed list),或者关联数组 (associative array)。 在 Java 语言中,我们可以将它理解成 HashMap或者对象。
  对象是一个无序的"'名称/值'对"集合。一个对象以"{"(左括号)开始,"}"(右括号)结束。每个“名称”后跟一            个":"(冒号);"'名称/值' 对"之间使用","(逗号)分隔。
示例:var json = {"name":"Jack","age":90,"Marray":true};


三、JSON-lib
Json-lib 是一个 Java 类库(官网:http://json-lib.sourceforge.net/)可以实现如下功能:

1、转换 JavaBean, Map, Collection, Java Array 和 XML 成为 JSON格式数据。
2、转换 JSON 格式数据成为 JavaBean对象、Map、Collection、List、Array等。

Json-lib可以将Java对象转成JSON格式的字符串,同样可以将JSON字符串转换成Java对象。

Json-lib 需要的 jar 包:

官方下载地址:http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/  【包含源码下载】

下载地址2:http://www.java2s.com/Code/Jar/j/Downloadjsonlib24jdk15sourcesjar.htm  【json-lib源码下载】

csdn下载地址http://download.csdn.net/detail/chenchunlin526/9810451 【全部jar包,还包括一个源码包

commons-beanutils-1.8.3.jar 【依赖包】
commons-collections-3.2.1.jar  【依赖包】
commons-lang-2.6.jar   【依赖包】
commons-logging-1.1.1.jar   【依赖包】
ezmorph-1.0.6.jar   【依赖包】

json-lib-2.4-jdk15.jar (最核心包)


四、JSON-lib 的使用

1. 将 Java数组/集合 序列化成Json对象。使用 JSONArray 可以序列化数组类型:

Java Array ---》JSON Array

Java List ---》JSON Array

Java Set ---》JSON Array

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONArray;

public class JsonLib {
   public static void main(String[] args) {
       /**
        * 将字符串数组解析成JSON对象
        */
       String[] str = { "Jack", "Tom", "90", "true" }; //字符串数组
       JSONArray json = JSONArray.fromObject(str); //将数组序列化成json对象
       System.err.println(json); //可以先将JSONArray类型的json对象转换成String类型再输出
       // System.out.println(json.toString());
       // ["Jack","Tom","90","true"]

       /**
        * 对像数组,注意数字和布而值
        */
       Object[] obj = { "北京", "上海", 89, true, 90.87 };
       JSONArray  json = JSONArray.fromObject(obj);
       System.err.println(json);
      // ["北京","上海",89,true,90.87]

      /**
        * 使用集合类List<T>
        */
       List<String> list = new ArrayList<String>();
       list.add("Jack");
       list.add("Rose");
       JSONArray  json = JSONArray.fromObject(list);
       System.err.println(json);
       // ["Jack","Rose"]
 
        /**
        * 使用 set 集
        */
       Set<Object> set = new HashSet<Object>();
       set.add("Hello");
       set.add(true);
       set.add(99);
       JSONArray json = JSONArray.fromObject(set);
       System.err.println(json);
      // [99,true,"Hello"]

   }
}
运行结果如下:

["Jack","Tom","90","true"]
["北京","上海",89,true,90.87]
["Jack","Rose"]
[99,true,"Hello"]

2. 将 JavaBean/Map 序列化成 JSON 对象。 使用JSONObject 解析:

JavaBean ---》JSON Object

Java Map ---》JSON Object

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
public class JsonLib {
   @SuppressWarnings("static-access")
   public static void main(String[] args) {
       /**
        * 解析Map/HashMap
        */
       Map<String, Object> map = new HashMap<String, Object>();
       map.put("name", "Tom");
       map.put("age", 33);
       JSONObject jsonObject = JSONObject.fromObject(map);
       System.out.println(jsonObject);
      //{"age":33,"name":"Tom"}

      /**
        * 解析 JavaBean
        */
       Person person = new Person("A001", "Jack"); //初始化Person对象
       JSONObject  jsonObject = JSONObject.fromObject(person);
       System.out.println(jsonObject);
      //{"id":"A001","name":"Jack"}

      /**
        * 解析嵌套的对象 Map<String, Object>
        */
       map.put("person", person);
       JSONObject  jsonObject = JSONObject.fromObject(map);
       System.out.println(jsonObject);
       // {"person":{"id":"A001","name":"Jack"},"age":33,"name":"Tom"}

   }
}
运行结果如下:

{"age":33,"name":"Tom"}
{"id":"A001","name":"Jack"}
{"person":{"id":"A001","name":"Jack"},"age":33,"name":"Tom"}

3. 使用 JsonConfig 过滤属性:适用于 JavaBean/Map

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class JsonLib {
   public static void main(String[] args) {
       JsonConfig config = new JsonConfig();
       config.setExcludes(new String[] { "name" }); //指定在转换时不包含哪些属性,此处排除name属性
       Person person = new Person("A001", "Jack"); // 初始化Person对象
       JSONObject jsonObject = JSONObject.fromObject(person, config); //在转换时传入之前的配置对象                          
       System.out.println(jsonObject);
      // {"id":"A001"}
   }
}

运行结果如下,在运行结果中我们可以看到 name 属性被过滤掉了:

{"id":"A001"}

实例2(过滤Bean对象中字段为空,或字段的值为空的字段
例:Test test = new Test();
    test.setId("1");
    test.setName("zhangsan");
    jsonObject.fromobject(test).toString;

输出:{"id":"1","name":"zhangsan"}

假如不封装name属性,只封装id属性
    Test test = new Test();
    test.setId("1");
    jsonObject.fromobject(test).toString;

输出:{"id":"1","name":""}
如果只输出:{"id":"1"} 这样的json字符,解决方法如下代码

public static void main(String[] args) {
  
    Test t = new Test();  
    t.id = 10;  
           
    JsonConfig jsonConfig = new JsonConfig();  
    PropertyFilter filter = new PropertyFilter() {  
            public boolean apply(Object object, String fieldName, Object fieldValue) {  
                return null == fieldValue || "" == fieldValue;  
            }  
    };  
    jsonConfig.setJsonPropertyFilter(filter);  
    System.out.println(JSONObject.fromObject(t, jsonConfig).toString());  
}  

如果未给对象赋值用fieldName即可,如果值默认为空,设置fieldValue即可。


4. 将 JSON对象解析成(反序列化) Java Array:

JSON Array ---》Java Array

import java.util.Arrays;
import net.sf.json.JSONArray;

public class JsonLib {
   public static void main(String[] args) {
       JSONArray jsonArray = JSONArray.fromObject("[89,90,99]"); //创建JSONArray
       Object array = JSONArray.toArray(jsonArray);//转换成Java Object
       System.out.println(array);
       // [Ljava.lang.Object;@1e5003f6
       System.out.println(Arrays.asList((Object[]) array));
       // [89, 90, 99]

   }
}
运行结果如下:

[Ljava.lang.Object;@1e5003f6
[89, 90, 99]

5. 将 Json对象解析成 JavaBean/Map(使用JSONObject的toBean()方法):

JSON Object ---》JavaBean

JSON Object ---》Map

import java.util.Map;
import net.sf.json.JSONObject;

public class JsonLib {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
       /**
        * 将 JSON 对象转换(解析)为 Map
        */
       String str = "{\"name\":\"Tom\",\"age\":90}";
       JSONObject jsonObject = JSONObject.fromObject(str);
       Map<String, Object> map = (Map<String, Object>) JSONObject.toBean(jsonObject, Map.class);
       System.out.println(map);
       // {age=90, name=Tom}


       /**
        * 将 JSON对象转换(解析)为 JavaBean
        */
       str = "{\"id\":\"A001\",\"name\":\"Jack\"}";
       jsonObject = JSONObject.fromObject(str);
       System.out.println(jsonObject);   //JSONObject类型:{age=90, name=Tom}
       Person person = (Person) JSONObject.toBean(jsonObject, Person.class);
       System.out.println(person);   //Person [id=A001, name=Jack]
   }
}

运行结果如下:

{age=90, name=Tom}
Person [id=A001, name=Jack]


在将 Json 形式的字符串转换为 JavaBean 的时候,需要注意 JavaBean 中必须有无参构造函数,否则会报如下找不到初始化方法的错误:

Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()
   at net.sf.json.JSONObject.toBean(JSONObject.java:288)
   at net.sf.json.JSONObject.toBean(JSONObject.java:233)
   at cn.sunzn.json.JsonLib.main(JsonLib.java:23)
Caused by: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()
   at java.lang.Class.getConstructor0(Unknown Source)
   at java.lang.Class.getDeclaredConstructor(Unknown Source)
   at net.sf.json.util.NewBeanInstanceStrategy$DefaultNewBeanInstanceStrategy.newInstance(NewBeanInstanceStrategy.java:55)
   at net.sf.json.JSONObject.toBean(JSONObject.java:282)
   ... 2 more

===================================================================================================================================

一、Java对象序列化成JSON对象

JSONObject是将Java对象转换(序列化)成一个JSON的Object形式,JSONArray是将一个Java对象转换(序列化)成JSON的Array格式。

那什么是JSON的Object形式、Array形式?--- 用通俗易懂的方法讲,所谓的JSON的Object形式,就是一个花括号里面存放的如Java Map的键值对,如:{name:’xiaoming’, age: 24};

那么JSON的Array形式呢?--- 就是中括号括起来的数组。如:[ 'json', true, 22];如果你还想了解更多json方面的知识,请看:http://www.json.org/json-zh.html除了上面的JSONArray、JSONObject可以将Java对象转换(序列化)成JSON(或是相反:将JSON字符串转换(反序列化))成Java对象)还有一个对象也可以完成上面的功能,它就是JSONSerializer;下面我们就来看看它们是怎么玩转Java对象和JSON的。

1、Java对象序列化成JSON对象【JSONSerializer、JsonConfig】

Java Bean ---》JSON Object

Java Bean ---》JSON Array

/**
 * 转换(序列化)Java Bean对象到JSON
 */
@Test
public void writeEntity2JSON() {

    fail("==============Java Bean >>> JSON Object==================");
    fail(JSONObject.fromObject(bean).toString());
    fail("==============Java Bean >>> JSON Array  ==================");
    fail(JSONArray.fromObject(bean).toString()); //array会在最外层套上[]
    fail("==============Java Bean >>> JSON Object ==================");
    fail(JSONSerializer.toJSON(bean).toString());
    
    fail("========================JsonConfig========================");
    JsonConfig jsonConfig = new JsonConfig();   
    jsonConfig.registerJsonValueProcessor(Birthday.class, new JsonValueProcessor() {
        public Object processArrayValue(Object value, JsonConfig jsonConfig) {
            if (value == null) {
                return new Date();
            }
            return value;
        }
 
        public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
            fail("key:" + key);
            return value + "##修改过的日期";
        }
 
    });
    jsonObject = JSONObject.fromObject(bean, jsonConfig);
    
    fail(jsonObject.toString());
    Student student = (Student) JSONObject.toBean(jsonObject, Student.class);
    fail(jsonObject.getString("birthday"));
    fail(student.toString());
    
    fail("-------------------------JsonPropertyFilter---------------------------");
    jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
        public boolean apply(Object source, String name, Object value) {
            fail(source + "%%%" + name + "--" + value);
            //忽略birthday属性
            if (value != null && Birthday.class.isAssignableFrom(value.getClass())) {
                return true;
            }
            return false;
        }
    });  
    fail(JSONObject.fromObject(bean, jsonConfig).toString());
    fail("-------------------------JavaPropertyFilter---------------------------");
    jsonConfig.setRootClass(Student.class);   
    jsonConfig.setJavaPropertyFilter(new PropertyFilter() {
        public boolean apply(Object source, String name, Object value) {
            fail(name + "@" + value + "#" + source);
            if ("id".equals(name) || "email".equals(name)) {
                value = name + "@@";
                return true;
            }
            return false;
        }
    });   
    //jsonObject = JSONObject.fromObject(bean, jsonConfig);
    //student = (Student) JSONObject.toBean(jsonObject, Student.class);
    //fail(student.toString());
    student = (Student) JSONObject.toBean(jsonObject, jsonConfig);
    fail("Student:" + student.toString());
}
fromObject将Java对象转换(序列化)成JSON对象,toBean将JSON对象转换(反序列化)成Java对象;
上面方法值得注意的是,使用了JsonConfig这个对象,这个对象可以在序列化的时候,对Java Object的数据进行处理、过滤等。上面的jsonConfigregisterJsonValueProcessor方法可以完成对对象值的处理和修改,比如处理生日为null时,给一个特定的值。同样setJsonPropertyFilter和setJavaPropertyFilter都是完成对转换后的值的处理。
运行上面的代码可以在控制台看到如下结果:

==============Java Bean >>> JSON Object==================
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
==============Java Bean >>> JSON Array==================
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}]
==============Java Bean >>> JSON Object ==================
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
========================JsonConfig========================
key:birthday
{"address":"address","birthday":"2010-11-22##修改过的日期","email":"email","id":1,"name":"haha"}

2010-11-22##修改过的日期
haha#1#address#null#email
-------------------------JsonPropertyFilter------------------------
haha#1#address#2010-11-22#email%%%address--address
haha#1#address#2010-11-22#email%%%birthday--2010-11-22
haha#1#address#2010-11-22#email%%%email--email
haha#1#address#2010-11-22#email%%%id--1
haha#1#address#2010-11-22#email%%%name--haha
{"address":"address","email":"email","id":1,"name":"haha"}
-------------------------JavaPropertyFilter------------------------
address@address#null#0#null#null#null
birthday@2010-11-22##修改过的日期#null#0#address#null#null
email@email#null#0#address#null#null
id@1#null#0#address#null#null
name@haha#null#0#address#null#null
Student:haha#0#address#null#null

2、 将Java List集合转换成JSON

Java List ---》JSON Array

/**
 * 转换Java List集合到JSON
 */
@Test
public void writeList2JSON() {
    fail("==============Java List >>> JSON Array==================");
    List<Student> stu = new ArrayList<Student>();
    stu.add(bean);
    bean.setName("jack");
    stu.add(bean);
    fail(JSONArray.fromObject(stu).toString());
    fail(JSONSerializer.toJSON(stu).toString());
}
运行此方法后,可以看到控制台输出:

==============Java List >>> JSON Array==================
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]

如果你是转换List集合,一定得用JSONArray或是JSONSrializer提供的序列化方法。如果你用JSONObject.fromObject方法转换List会出现异常,通常使用JSONSrializer这个JSON序列化的方法,它会自动识别你传递的对象的类型,然后转换成相应的JSON字符串。

3、 将Map集合转换成JSON对象

Java Map ---》JSON Object

/**
 * 转Java Map对象到JSON
 */
@Test
public void writeMap2JSON() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("A", bean);
    
    bean.setName("jack");
    map.put("B", bean);
    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]; }"); 
    fail("==============Java Map >>> JSON Object==================");
    fail(JSONObject.fromObject(map).toString());
    fail("==============Java Map >>> JSON Array ==================");
    fail(JSONArray.fromObject(map).toString());
    fail("==============Java Map >>> JSON Object==================");
    fail(JSONSerializer.toJSON(map).toString());
}
上面的Map集合有JavaBean、String、Boolean、Integer、以及Array和js的function函数的字符串。

运行上面的程序,结果如下:

==============Java Map >>> JSON Object==================
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}
==============Java Map >>> JSON Array ==================
[{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}]
==============Java Map >>> JSON Object==================
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}

4、 将更多类型转换成JSON

**
 * 转换更多数组类型到JSON
 */
@Test
public void writeObject2JSON() {
    String[] sa = {"a", "b", "c"};
    fail("==============Java StringArray >>> JSON Array ==================");
    fail(JSONArray.fromObject(sa).toString());
    fail(JSONSerializer.toJSON(sa).toString());
    fail("==============Java boolean Array >>> JSON Array ==================");
    boolean[] bo = { true, false, true };
    fail(JSONArray.fromObject(bo).toString());
    fail(JSONSerializer.toJSON(bo).toString());
    Object[] o = { 1, "a", true, 'A', sa, bo };
    fail("==============Java Object Array >>> JSON Array ==================");
    fail(JSONArray.fromObject(o).toString());
    fail(JSONSerializer.toJSON(o).toString());
    fail("==============Java String >>> JSON ==================");
    fail(JSONArray.fromObject("['json','is','easy']").toString());
    fail(JSONObject.fromObject("{'json':'is easy'}").toString());
    fail(JSONSerializer.toJSON("['json','is','easy']").toString());
    fail("==============Java JSONObject >>> JSON ==================");
    jsonObject = new JSONObject()   
        .element("string", "JSON")
        .element("integer", "1")
        .element("double", "2.0")
        .element("boolean", "true");  
    fail(JSONSerializer.toJSON(jsonObject).toString());
    
    fail("==============Java JSONArray >>> JSON ==================");
    jsonArray = new JSONArray()   
        .element( "JSON" )   
        .element( "1" )   
        .element( "2.0" )   
        .element( "true" ); 
    fail(JSONSerializer.toJSON(jsonArray).toString());
    
    fail("==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================");
    List input = new ArrayList();   
    input.add("JSON");
    input.add("1");
    input.add("2.0");
    input.add("true");   
    JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );   
    JsonConfig jsonConfig = new JsonConfig();   
    jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );   
    Object[] output = (Object[]) JSONSerializer.toJava(jsonArray, jsonConfig);
    System.out.println(output[0]);
    
    fail("==============Java JSONFunction >>> JSON ==================");
    String str = "{'func': function( param ){ doSomethingWithParam(param); }}";   
    JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str);   
    JSONFunction func = (JSONFunction) jsonObject.get("func");   
    fail(func.getParams()[0]);   
    fail(func.getText() );   
}

运行后结果如下:

==============Java StringArray >>> JSON Array ==================
["a","b","c"]
["a","b","c"]
==============Java boolean Array >>> JSON Array ==================
[true,false,true]
[true,false,true]
==============Java Object Array >>> JSON Array ==================
[1,"a",true,"A",["a","b","c"],[true,false,true]]
[1,"a",true,"A",["a","b","c"],[true,false,true]]
==============Java String >>> JSON ==================
["json","is","easy"]
{"json":"is easy"}
["json","is","easy"]
==============Java JSONObject >>> JSON ==================
{"string":"JSON","integer":"1","double":"2.0","boolean":"true"}
==============Java JSONArray >>> JSON ==================
["JSON","1","2.0","true"]
==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================
JSON
==============Java JSONFunction >>> JSON ==================
param
doSomethingWithParam(param);

这里还有一个JSONFunction的对象,可以转换JavaScript的function。可以获取方法参数和方法体。

同时,还可以用JSONObject、JSONArray构建Java对象,完成Java对象到JSON字符串的转换。

二、JSON对象反序列化成Java对象

1、 将json字符串转成Java对象(json字符串先转换成JSON对象,然后再转换成Java对象

JSON Object ---》Java Bean

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," +
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
/**
 * 将json字符串转化为java对象
 */
@Test
public void readJSON2Bean() {
    fail("==============JSON Object String >>> Java Bean ==================");
    JSONObject jsonObject = JSONObject.fromObject(json);
    Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
    fail(stu.toString()); //tom#22#chian#2010-11-22#email@123.com
}
运行后,结果如下:

====================JSON Object String >>> Java Bean ==================
tom#22#chian#2010-11-22#email@123.com

实例2,把json对象转换成复杂bean对象

JSON Object ---》Java Bean

public class TranslateResult {  
    private String from;    // 实际采用的源语言    
    private String to;  // 实际采用的目标语言  
    private List<ResultPair> transResult;    // 结果体    
} 
====

public class ResultPair {  
    private String src; // 原文  
    private String dst; // 译文  
}  
核心代码:

StringBuffer sb = new StringBuffer(); 
 
String json = "{\"from\":\"en\",\"to\":\"zh\",\"transResult\":[{\"src\":\"hello\",\"dst\":\"您好\"},{\"src\":\"beautiful\",\"dst\":\"美女\"}]}";
JSONObject jsonObject = JSONObject.fromObject(json)
Map<String, Class<ResultPair>> clazzMap = new HashMap<String, Class<ResultPair>>();  
map.put("transResult", ResultPair.class);  
TranslateResult translateResult = (TranslateResult) JSONObject.toBean(jsonObject, TranslateResult.class, clazzMap);  
List<ResultPair> list = translateResult.getTransResult();  
for (ResultPair rp : list) {  
    sb.append(rp.getDst());  
}  
System.out.println(sb); // 输出:你好美女 

2、将json字符串转换成动态Java对象(MorphDynaBean)

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2DynaBean() {
    try {
        fail("==============JSON Object String >>> Java MorphDynaBean ==================");
        JSON jo = JSONSerializer.toJSON(json);
        Object o = JSONSerializer.toJava(jo);//MorphDynaBean
        fail(PropertyUtils.getProperty(o, "address").toString()); //chian
        jsonObject = JSONObject.fromObject(json);
        fail(jsonObject.getString("email"));
        o = JSONSerializer.toJava(jsonObject);//MorphDynaBean
        fail(PropertyUtils.getProperty(o, "name").toString());
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}
转换后的对象Object是一个MorphDynaBean的动态JavaBean,通过PropertyUtils可以获得指定的属性的值。

运行后结果如下:

==============JSON Object String >>> Java MorphDynaBean =============
chian
email@123.com
tom

3、将json字符串转成Java的Array数组

JSON Array ---》Java Array ---》Java bean

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2Array() {
    try {
        fail("==============JSON Arry String >>> Java Array ==================");
        json = "[" + json + "]";
        jsonArray = JSONArray.fromObject(json);
        fail("#%%%" + jsonArray.get(0).toString());
        Object[] os = jsonArray.toArray();
        System.out.println(os.length); // 1
        
        fail(JSONArray.fromObject(json).join(""));
    //{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
        fail(os[0].toString());
    //{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
        Student[] stus = (Student[]) JSONArray.toArray(jsonArray, Student.class);
        System.out.println(stus.length); //1
        System.out.println(stus[0]);  //tom#22#chian#2010-11-22#email@123.com
    } catch (Exception e) {
        e.printStackTrace();
    }
}
运行的结果如下:

==============JSON Arry String >>> Java Array ==================
#%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
tom#22#chian#2010-11-22#email@123.com

4、将JSON字符串转成Java的List集合已不推荐使用

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2List() {
    try {
        fail("==============JSON Arry String >>> Java List ==================");
        json = "[" + json + "]";
        jsonArray = JSONArray.fromObject(json);
        List<Student> list = JSONArray.toList(jsonArray, Student.class);
        System.out.println(list.size()); //1
        System.out.println(list.get(0)); //tom#22#chian#2010-11-22#email@123.com
        
        list = JSONArray.toList(jsonArray);
        System.out.println(list.size()); // 1
        System.out.println(list.get(0));//MorphDynaBean 
//net.sf.ezmorph.bean.MorphDynaBean@141b571[{id=22,birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[{birthday=2010-11-22}], address=chian, email=email@123.com, name=tom}]
    } catch (Exception e) {
        e.printStackTrace();
    }
}
运行后结果如下:

==============JSON Arry String >>> Java List ==================
1
tom#22#chian#2010-11-22#email@123.com
1
net.sf.ezmorph.bean.MorphDynaBean@141b571[
  {id=22, birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[
  {birthday=2010-11-22}
], address=chian, email=email@123.com, name=tom}
]

5、将json字符串转换成Collection接口

JSON Array ---》Java Collection ---》Java Bean

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2Collection() {
    try {
        fail("==============JSON Array String >>> Java Collection ==================");
        json = "[" + json + "]";
        jsonArray = JSONArray.fromObject(json);
        Collection<Student> con = JSONArray.toCollection(jsonArray, Student.class);
        System.out.println(con.size()); //1
        Object[] stt = con.toArray();
        System.out.println(stt.length); // 1
        fail(stt[0].toString()); // tom#22#chian#2010-11-22#email@123.com
        
    } catch (Exception e) {
        e.printStackTrace();
    }
}
刚才上面的将json转换成list提示该方法过时,这里有toCollection,可以用此方法代替toList方法;运行后结果如下:

==============JSON Arry String >>> Java Collection ==================
1
1
tom#22#chian#2010-11-22#email@123.com

6、将json字符串转换成Map集合

复杂JSON类型---》Map

@Test
public void readJSON2Map() {
    try {
        fail("==============JSON Array String >>> Java Map ==================");
        json = "{\"arr\":[\"a\",\"b\"],\"A\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"int\":1,"+
        "\"B\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"name\":\"json\",\"bool\":true}";
        jsonObject = JSONObject.fromObject(json);

        Map<String, Class<?>> clazzMap = new HashMap<String, Class<?>>();
        clazzMap.put("arr", String[].class);
        clazzMap.put("A", Student.class);
        clazzMap.put("B", Student.class);
        Map<String, ?> mapBean = (Map) JSONObject.toBean(jsonObject, Map.class, clazzMap); //关键代码
        System.out.println(mapBean);
// {A=jack#1#address#2010-11-22#email, arr=[a, b], B=jack#1#address#2010-11-22#email, int=1, name=json, bool=true}
        
        Set<String> set = mapBean.keySet();
        Iterator<String> iter = set.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            fail(key + ":" + mapBean.get(key).toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
运行后结果如下:

==============JSON Arry String >>> Java Map ==================
{A=jack#1#address#2010-11-22#email, arr=[a, b], B=jack#1#address#2010-11-22#email, int=1, name=json, bool=true}
A:jack#1#address#2010-11-22#email
arr:[a, b]
B:jack#1#address#2010-11-22#email
int:1
name:json
bool:true


题外话json-lib已经停止更新了(jdk1.5之后就没有更新过了),而且他的相关依赖包比较多(有5个依赖包,1个核心包),所以在新的项目开发中是不建议使用的,尤其是新的互联网项目中最好别用这个库,主要是他的性能比较差、速度慢。但是在一些需求比较简单的项目中还是可以用的,笔者的公司的很多老项目也在用。其实他的api方法还是比较好用的,也比较直观,易于理解。

目前,其他一些主流JSON库的性能已远远超过他。主流的优秀json解析库有:

1、Jackson(SpringMVC框架官方默认的json解析包,功能强大,性能优秀,不过api不怎么直观)

2、Gson(google公司开的,性能优秀,稳定性好)

3、Fastjson(阿里巴巴开发的,号称目前解析速度的最快的json库,api使用简单,易上手,性能好)等。

上面这三个库才是目前Java领域json解析库中,最牛B的三个库。排在第一梯队,性能不相上下。接下来的博文系列会分别讲解这三个库的使用方法。


 类似资料: