Java代码
String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
JSONObject jsonObject = JSONObject.fromString(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" ) );
assertEquals( expected, (List) PropertyUtils.getProperty( bean, "array" ) );
Java代码
String json = "{\"value\":\"xx\",\"row\":1,\"col\":1}";
JSONObject jsonObject = JSONObject.fromString(json);
JsonBean2 bean = (JsonBean2) JSONObject.toBean( jsonObject, JsonBean2.class );
assertEquals( jsonObject.get( "col" ),new Integer( bean.getCol()) );
assertEquals( jsonObject.get( "row" ), new Integer( bean.getRow() ) );
assertEquals( jsonObject.get( "value" ), bean.getValue() );
6 json to xml
1)
JSONObject json = new JSONObject( true );
String xml = XMLSerializer.write( json );
<o null="true">
2)
JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");
String xml = XMLSerializer.write( json );
<o>
<name type="string">json</name>
<bool type="boolean">true</bool>
<int type="number">1</int>
</o>
<o>
<name type="string">json</name>
<bool type="boolean">true</bool>
<int type="number">1</int>
</o>
3)
JSONArray json = JSONArray.fromObject("[1,2,3]");
String xml = XMLSerializer.write( json );
<a>
<e type="number">1</e>
<e type="number">2</e>
<e type="number">3</e>
</a>
7 、xml to json
<a>
<e type="function" params="i,j">
return matrix[i][j];
</e>
</a>
<a>
<e type="function" params="i,j">
return matrix[i][j];
</e>
</a>
JSONArray json = (JSONArray) XMLSerializer.read( xml );
System.out.println( json );
// prints [function(i,j){ return matrix[i][j]; }]