what's json-lib
JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.
It is based on the work by Douglas Crockford in http://www.json.org/java.
The following tables sumarizes the types conversion between java and javascript:
How to use json-lib
Using the JSONSerializer
Working with arrays and collections
Working with objects
Working with XML
Using the JSONSerializer
JSONSerializer can transform any java object to JSON notation and back with a simple and clean interface, leveraging all the builders in JSONObject and JSONArray. To transform a java obect into JSON use JSONSerializer.toJSON(). To transform a valid JSON value (by JSON, I mean an Object implementing that interface), use toJava(). The last method is an instance method because the serializer needs special configuration to transform a JSON value to a bean class, array, List or DynaBean.
Working with arrays and collections
The simplest way to create a JSONArray from a java array or collection is through the static factory methods from JSONArray. JSONArray.fromObject() will inspect its parameter and call the correct factory or constructor.
Examples:
boolean[] boolArray = new boolean[]{true,false,true};
JSONArray jsonArray = JSONArray.fromObject( boolArray );
System.out.println( jsonArray );
// prints [true,false,true]
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray = JSONArray.fromObject( list );
System.out.println( jsonArray );
// prints ["first","second"]
JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );
System.out.println( jsonArray );
// prints ["json","is","easy"]
Working with objects
From Beans & Maps to JSON
The simplest way to create a JSONObject from a bean or Map is through the static factory methods from JSONObject. JSONObject.fromObject() will inspect its parameter and call the correct factory or constructor.
Examples:
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( jsonObject );
// prints ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i){ return this.arr[i]; }]
class MyBean{
private String name = "json";
private int pojoId = 1;
private char[] options = new char[]{'a','f'};
private String func1 = "function(i){ return this.options[i]; }";
private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");
// getters & setters
...
}
JSONObject jsonObject = JSONObject.fromObject( new MyBean() );
System.out.println( jsonObject );
// prints {"name":"json","pojoId":1,"options":["a","f"],
"func1":function(i){ return this.options[i];},
"func2":function(i){ return this.options[i];}}
CAUTION: when parsing, neither JSONObject nor JSONArray checks for cycles in the hierarchy. It is a task left for the user of the library.
From JSON to Beans
Json-lib can transform JSONObjects to either a DynaBean or an specific bean class.
When using DynaBean all arrays are converted to Lists, when using an specific bean class the transformation will use type conversion if necessary on array properties.
Convert to DynaBean:
String json = "{name=/"json/",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
JSONObject jsonObject = new JSONObject( json );
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" ) );
List expected = JSONArray.toList( jsonObject.getJSONArray( "array" ) );
Assertions.assertListEquals( expected, (List) PropertyUtils.getProperty( bean, "array" ) );
Convert to Bean:
String json = "{bool:true,integer:1,string:/"json/"}";
JSONObject jsonObject = new JSONObject( json );
BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class );
assertEquals( jsonObject.get( "bool" ), Boolean.valueOf( bean.isBool() ) );
assertEquals( jsonObject.get( "integer" ), new Integer( bean.getInteger() ) );
assertEquals( jsonObject.get( "string" ), bean.getString() );
There are two special cases when converting to an specific bean, if the target bean has a Map property and it must contain other beans, JSONObject.toBean() will transform the nested beans into DynaBeans. If you need those nested beans transformed into an specific class, you can either postprocess the Map attribute or provide hints on JSONObject's attributes for conversion. JSONObject.toBean() may be passed a third argument, a Map, that will provide thos hints. Every key must be either the name of a property or a regular expression matching the object's properties, and the value must be a Class.
The second case is similar and it happens when the target bean has a Collection (List) as a property and it must contain other beans. In this case there is no way to provide hints for class conversion. The only possible solution is to postprocess the collection transforming each DynaBean into an specific bean.
To ease the postprocessing scenarios, Json-lib provides a Morpher capable of transforming a DynaBean into an specific bean, DynaBeanToBeanMorpher
Example:
class MyBean{
private List data;
// getters & setters
}
class Person{
private String name;
// getters & setters
}
...
String json = "{'data':[{'name':'Wallace'},{'name':'Grommit'}]}";
MyBean bean = JSONObject.toBean( json, MyBean.class );
This yields a MyBean instance that has DynaBeans inside the 'data' attribute', so now comes the part of postprocessing, this can be done with an Iterator
Example:
Morpher dynaMorpher = new DynaBeanToBeanMorpher( Person.class, JSONUtils.getMorpherRegistry() );
morpherRegistry.registerMorpher( dynaMorpher );
List output = new ArrayList();
for( Iterator i = bean.getData().iterator(); i.hasNext(); ){
output.add( morpherRegistry.morph( Person.class, i.next() ) );
}
bean.setData( output );
To learn more about Morphers, please visit EZMorph's project site.
Working with XML
From JSON to XML
Transforming JSONObjects and JSONArrays to XML is as simple as a call to XMLSerializer.write().
XMLSerializer will append special attributes to each xml element for easing the transformation back to JSON.
JSONObject json = new JSONObject( true );
String xml = XMLSerializer.write( json );
System.out.println( xml );
// prints
<o class="object" null="true"></o>
JSONObject json = JSONObject.fromObject("{/"name/":/"json/",/"bool/":true,/"int/":1}");
String xml = XMLSerializer.write( json );
System.out.println( xml );
// prints
<o class="object">
<name type="string">json</name>
<bool type="boolean">true</bool>
<int type="number">1</int>
</o>
JSONArray json = JSONArray.fromObject("[1,2,3]");
String xml = XMLSerializer.write( json );
System.out.println( xml );
// prints
<a class="array">
<e type="number">1</e>
<e type="number">2</e>
<e type="number">3</e>
</a>
From XML to JSON
XMLSerializer treats each element as a string unless a type parameter is specified.
JSONFunction needs an additional parameter that specifies that function's params.
<a class="array">
<e type="function" params="i,j">
return matrix[i][j];
</e>
</a>
JSONArray json = XMLSerializer.read( xml );
System.out.println( json );
// prints [function(i,j){ return matrix[i][j]; }]
CAUTION: when parsing, neither JSONObject nor JSONArray checks for cycles in the hierarchy. It is a task left for the user of the library.
使用json-lib需要的包,见
http://blog.csdn.net/yethyeth/archive/2006/12/18/1447593.aspx
分享到:
相关推荐
json-lib-2.4-jdk15.jar下载,json-lib是一款简单易用的Java JSON库。它可以将Java对象转换成JSON字符串,也可以将JSON字符串转换成Java对象。json-lib体积小、无依赖,性能表现也不错,适合在各种Java项目中使用。 ...
1、json的核心包:json-lib-2.4-jdk15.jar; 2、json-lib-2.4-jdk15.jar依赖的jar包:commons-beanutils-1.9.3.jar,commons-collections-3.2.2.jar,commons-lang-2.6.jar,commons-logging-1.2.jar,ezmorph-1.0.6...
里面包含json-lib所需的全部jar文件. json-lib-2.1-jdk15.jar ezmorph-1.0.3.jar commons-beanutils.jar commons-collections-3.2.1.jar commons-lang-2.4.jar commons-logging-1.1.1.jar
json-lib-2.4-jdk15所需全部JAR包,资源清单 json-lib-2.4-jdk15.jar 依赖: ezmorph-1.0.6.jar commons-beanutils-1.8.3.jar commons-lang-2.5.jar morph-1.1.1.jar commons-logging-1.1.1.jar commons-collections-...
json-lib-2.4-jdk15依赖的库文件: 压缩包内容: commons-beanutils-1.8.0.jar commons-collections-3.1.jar commons-lang-2.5.jar commons-logging-1.1.1.jar ezmorph-1.0.6.jar json-lib-2.4-jdk15-javadoc.jar ...
json架包,包好json-lib-2.2.3-jdk13.jar,json-lib-2.4-jdk14.jar以及附带的支持包ezmorph-1.0.6.jar,commons-logging.jar,commons-lang.jar等
json的核心包:json-lib-2.4-jdk15.jar;json-2.4所依赖的jar包:commons-beanutils-1.8.0.jar,commons-collections-3.2.1.jar,commons-lang-2.5.jar,commons-logging-1.1.1.jar,ezmorph-1.0.6.jar;以及和...
json基础jar包,包含json-lib-2.3-jdk15.jar源码
json-lib-2.4-jdk15-sources.jar 是net.sf.json-lib-jdk15-2.4的源码文件
使用json-lib实现json与Java对象的互转
json-lib-2.3-jdk15开发包和所有依赖包
json-lib-2.4-jdk15和全部依赖jar包 所需要的开发工具
<groupId>net.sf.json-lib</groupId> <artifactId>json-lib <version>2.4 <classifier>jdk15 或者直接下载这个包
json-lib-2.4-jdk15.jar json-lib-2.4-jdk15-sources.jar json-lib-2.4-jdk15-javadoc.jar 包含文件有:json-lib-2.4-jdk15.jar json-lib-2.4-jdk15-sources.jar json-lib-2.4-jdk15-javadoc.jar
ezmorph-1.0.6.jar和json-lib-2.2.2-jdk15.rar
JSON-lib包json-lib-0.8.jar和json-lib-0.9.jar包
json-lib-1.1-jdk13-javadoc,欢迎下载。
jar包如下:commons-beanutils-1.7,commons-collections,commons-lang,commons-logging-1.1.1,ezmorph, gson-2.2.1,gson-2.2.1-sources,json-lib-2.2.2-jdk15
官网发布的json-lib-2.4-jdk13.jar,在JDK1.4中无法使用,经过不懈努力,知道问题出在哪里了,分享下: debug那个json-lib源码,最后错误定位在这个方法 protected static void removeInstance( Object instance ) ...