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

JSON之json-lib解析

康元凯
2023-12-01

一、json-lib依赖包

Json-lib requires (at least) the following dependencies in your classpath:

  • jakarta commons-lang 2.5
  • jakarta commons-beanutils 1.8.0
  • jakarta commons-collections 3.2.1
  • jakarta commons-logging 1.1.1
  • ezmorph 1.0.6
Other dependencies are needed if working with XML andGroovy. Please review the  Dependencies report  to know more about those extra dependencies.


二、代码示例

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框架好用。

 类似资料: