JSON与JAVA的数据转换--String->Bean

5、String to bean
    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 eXP ected = JSONArray.toList( jsonObject.getJSONArray( "array" ) );       
     assertEquals( exp ected, (List) PropertyUtils.getProperty( bean, "array" ) );      
 
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 exp ected = JSONArray.toList( jsonObject.getJSONArray( "array" ) );     
  assertEquals( exp ected, (List) PropertyUtils.getProperty( bean, "array" ) );     
 
  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() );      
 
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() );     

你可能感兴趣的:(java,bean,json)