一、json-lib依赖包
Json-lib requires (at least) the following dependencies in your classpath:
二、代码示例
public static void main(String[] args){
//数组与集合
boolean[] boolArray = new boolean[]{true,false,true};
JSONArray jsonArray = JSONArray.fromObject( boolArray );
System.out.println( jsonArray );
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
jsonArray = JSONArray.fromObject( list );
System.out.println( jsonArray );
jsonArray = JSONArray.fromObject( "['json','is','easy']" );
System.out.println( jsonArray );
//from Bean & Map to json
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 );
// prints ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i){ return this.arr[i]; }]
//from JSON to Beans
String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
jsonObject = JSONObject.fromObject( 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" ) );
String json = "{bool:true,integer:1,string:\"json\"}";
jsonObject = JSONObject.fromObject( 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() ); */
}
PS:依赖包太多,相对操作和转换都不如其他几个json框架好用。