本文介绍如何使用JSON-lib这个Java类包实现Java的数据转换。通过此类包可以把bean,map和XML转换成JSON并能够把JSON转回成bean和DynaBean。
JSON-lib这个Java类包用于把bean,map和XML转换成JSON并能够把JSON转回成bean和DynaBean。
下载地址:
http://sourceforge.net/projects/json-lib/
还要需要的第3方包:
org.apache.commons
包括:
commons-beanutils.jar
commons-collections-3.2.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
net.sf.ezmorph(ezmorph-1.0.6.jar)
1. 对List类型的解析:
Java代码:
- boolean[] boolArray = new boolean[]{true,false,true};
- JSONArray jsonArray1 = JSONArray.fromObject( boolArray );
- System.out.println( jsonArray1 );
- // prints [true,false,true]
-
- List list = new ArrayList();
- list.add( "first" );
- list.add( "second" );
- JSONArray jsonArray2 = JSONArray.fromObject( list );
- System.out.println( jsonArray2 );
- // prints ["first","second"]
-
- JSONArray jsonArray3 = JSONArray.fromObject( "['json','is','easy']" );
- System.out.println( jsonArray3 );
- // prints ["json","is","easy"]
2. 对Map类型的解析
原文参考自站长网:http://www.software8.co/wzjs/java/3165.html
Java代码:
- 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 json = JSONObject.fromObject(map);
- System.out.println(json);
- // {"arr":["a","b"],"int":1,"name":"json","func":function(i){ return this.arr[i]; },"bool":true}
3、对JavaBEAN的解析
Java代码:
- import net.sf.json.*;
-
- public class Test {
-
- public static class JsonBean{
- private String name="json";
- private int pojoId = 1;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getPojoId() {
- return pojoId;
- }
- public void setPojoId(int pojoId) {
- this.pojoId = pojoId;
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
- System.out.println(jsonObject);
- // {"name":"json","pojoId":1}
- }
- }
说明apache json-lib可以满足各种json的解析。