JSON与JAVA数据的转换

JSON-lib这个Java类包用于把bean,map和XML转换成JSON并能够把JSON转回成bean和DynaBean。

下载地址:http://json-lib.sourceforge.net/
还要需要的第3方包:
org.apache.commons(3.2以上版本)
org.apache.oro
net.sf.ezmorph(ezmorph-1.0.4.jar)
nu.xom

1、List

Java代码
  1. boolean [] boolArray = new boolean []{ true , false , true };      
  2.             JSONArray jsonArray1 = JSONArray.fromObject( boolArray );      
  3.             System.out.println( jsonArray1 );      
  4.             // prints [true,false,true]     
  5.               
  6.             List list = new ArrayList();      
  7.             list.add( "first" );      
  8.             list.add( "second" );      
  9.             JSONArray jsonArray2 = JSONArray.fromObject( list );      
  10.             System.out.println( jsonArray2 );      
  11.             // prints ["first","second"]     
  12.   
  13.             JSONArray jsonArray3 = JSONArray.fromObject( "['json','is','easy']" );      
  14.             System.out.println( jsonArray3 );      
  15.             // prints ["json","is","easy"]      
boolean[] boolArray = new boolean[]{true,false,true};
JSONArray jsonArray1 = JSONArray.fromObject( boolArray );
System.out.println( jsonArray1 );
// prints [true,false,true]
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list );
System.out.println( jsonArray2 );
// prints ["first","second"]
JSONArray jsonArray3 = JSONArray.fromObject( "['json','is','easy']" );
System.out.println( jsonArray3 );
// prints ["json","is","easy"]


2、Map

Java代码
  1. Map map = new HashMap();      
  2.           map.put( "name" , "json" );      
  3.           map.put( "bool" , Boolean.TRUE );      
  4.             
  5.           map.put( "int" , new Integer( 1 ) );      
  6.           map.put( "arr" , new String[]{ "a" , "b" } );      
  7.           map.put( "func" , "function(i){ return this.arr[i]; }" );      
  8.           JSONObject json = JSONObject.fromObject( map );      
  9.           System.out.println( json );      
  10.           //{"func":function(i){ return this.arr[i]; },"arr":["a","b"],"int":1,"name":"json","bool":true}   
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( json );
//{"func":function(i){ return this.arr[i]; },"arr":["a","b"],"int":1,"name":"json","bool":true}


3、BEAN

Java代码
  1. /**
  2.       * Bean.java
  3.          private String name = "json";   
  4.          private int pojoId = 1;   
  5.          private char[] options = new char[]{'a','f'};   
  6.          private String func1 = "function(i){ return this.options[i]; }";   
  7.          private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");
  8.      */   
  9. JSONObject jsonObject = JSONObject.fromObject( new JsonBean() );      
  10. System.out.println( jsonObject );      
  11. //{"func1":function(i){ return this.options[i]; },"pojoId":1,"name":"json","options":["a","f"],"func2":function(i){ return this.options[i]; }}     
/**
* Bean.java
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];");
*/
JSONObject jsonObject = JSONObject.fromObject( new JsonBean() );
System.out.println( jsonObject );
//{"func1":function(i){ return this.options[i]; },"pojoId":1,"name":"json","options":["a","f"],"func2":function(i){ return this.options[i]; }}


4、BEANS

Java代码
  1. /**
  2.        * private int row ;
  3.            private int col ;
  4.            private String value ;
  5.        *
  6.        */   
  7. List list = new ArrayList();   
  8.           JsonBean2 jb1 = new JsonBean2();   
  9.           jb1.setCol( 1 );   
  10.           jb1.setRow( 1 );   
  11.           jb1.setValue( "xx" );   
  12.             
  13.           JsonBean2 jb2 = new JsonBean2();   
  14.           jb2.setCol( 2 );   
  15.           jb2.setRow( 2 );   
  16.           jb2.setValue( "" );   
  17.             
  18.             
  19.           list.add(jb1);   
  20.           list.add(jb2);   
  21.             
  22.           JSONArray ja = JSONArray.fromObject(list);   
  23.           System.out.println( ja.toString() );   
  24.           //[{"value":"xx","row":1,"col":1},{"value":"","row":2,"col":2}]   
/**
* private int row ;
private int col ;
private String value ;
*
*/
List list = new ArrayList();
JsonBean2 jb1 = new JsonBean2();
jb1.setCol(1);
jb1.setRow(1);
jb1.setValue("xx");
JsonBean2 jb2 = new JsonBean2();
jb2.setCol(2);
jb2.setRow(2);
jb2.setValue("");
list.add(jb1);
list.add(jb2);
JSONArray ja = JSONArray.fromObject(list);
System.out.println( ja.toString() );
//[{"value":"xx","row":1,"col":1},{"value":"","row":2,"col":2}]


5、String to bean

Java代码
  1. String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}" ;      
  2. JSONObject jsonObject = JSONObject.fromString(json);      
  3. Object bean = JSONObject.toBean( jsonObject );      
  4. assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) );      
  5.    assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) );      
  6.    assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) );      
  7.     assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) );      
  8.     assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) );      
  9.    List expected = JSONArray.toList( jsonObject.getJSONArray( "array" ) );      
  10.    assertEquals( expected, (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 expected = JSONArray.toList( jsonObject.getJSONArray( "array" ) );
assertEquals( expected, (List) PropertyUtils.getProperty( bean, "array" ) );

 

Java代码
  1. String json = "{\"value\":\"xx\",\"row\":1,\"col\":1}" ;      
  2. JSONObject jsonObject = JSONObject.fromString(json);   
  3.    JsonBean2 bean = (JsonBean2) JSONObject.toBean( jsonObject, JsonBean2. class );      
  4.     assertEquals( jsonObject.get( "col" ), new Integer( bean.getCol())   );      
  5.       assertEquals( jsonObject.get( "row" ), new Integer( bean.getRow() ) );      
  6.       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() );



6 json to xml
1)
JSONObject json = new JSONObject( true );
String xml = XMLSerializer.write( json );

<o class="object" null="true">

2)
JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");
String xml = XMLSerializer.write( json );
<o class="object">
<name type="string">json</name>
<bool type="boolean">true</bool>
<int type="number">1</int>
</o>
<o class="object">
<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 class="array">
<e type="number">1</e>
<e type="number">2</e>
<e type="number">3</e>
</a>

7 、xml to json
<a class="array">
<e type="function" params="i,j">
return matrix[i][j];
</e>
</a>
<a class="array">
<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]; }]

 

 

如果需要解析的数据间存在级联关系,而互相嵌套引用,在hibernate中极容易嵌套而抛出net.sf.json.JSONException: There is a cycle in the hierarchy异常。


 
解决办法

1.设置JSON-LIB让其过滤掉引起循环的字段。
Java代码 复制代码
  1. JsonConfig config =  new  JsonConfig();   
  2. config.setIgnoreDefaultExcludes( false );      
  3. config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);    
  4. config.registerJsonValueProcessor(Date. class , new  DateJsonValueProcessor( "yyyy-MM-dd" ));  //date processor register   
  5. config.setExcludes( new  String[]{ //只要设置这个数组,指定过滤哪些字段。   
  6.    "consignee" ,   
  7.    "contract" ,   
  8.    "coalInfo" ,   
  9.    "coalType" ,   
  10.    "startStation" ,   
  11.    "balanceMan" ,   
  12.    "endStation"   
  13. });   
  14. String tempStr =  "{\"TotalRecords\":" + total.toString() + ",\"Datas\":" +JSONSerializer.toJSON(list,config).toString()+ "}" ;   
  15. out.print(tempStr);  
  JsonConfig config = new JsonConfig();
  config.setIgnoreDefaultExcludes(false);   
  config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); 
  config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd")); //date processor register
  config.setExcludes(new String[]{//只要设置这个数组,指定过滤哪些字段。
    "consignee",
    "contract",
    "coalInfo",
    "coalType",
    "startStation",
    "balanceMan",
    "endStation"
  });
  String tempStr = "{\"TotalRecords\":"+ total.toString() +",\"Datas\":"+JSONSerializer.toJSON(list,config).toString()+"}";
  out.print(tempStr);
 
 
2.设置JSON-LIB的setCycleDetectionStrategy属性让其自己处理循环,省事但是数据过于复杂的话会引起数据溢出或者效率低下。
Java代码 复制代码
  1. JsonConfig config =  new  JsonConfig();   
  2. config.setIgnoreDefaultExcludes( false );      
  3. config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);    
  4. config.registerJsonValueProcessor(Date. class , new  DateJsonValueProcessor( "yyyy-MM-dd" ));  //date processor register   
  5. String tempStr =  "{\"TotalRecords\":" + total.toString() + ",\"Datas\":" +JSONSerializer.toJSON(list,config).toString()+ "}" ;   
  6. out.print(tempStr); 

json-lib-2.2可以为对应的class注册解析类,记住一定要2.2,2.1有同步问题。切记切记。
写一个DateJsonValueProcessor.java

Java代码
  1. package  anni.core.web.json;  
  2.   
  3. import  java.text.DateFormat;  
  4. import  java.text.SimpleDateFormat;  
  5.   
  6. import  java.util.Date;  
  7.   
  8. import  net.sf.json.JSONObject;  
  9. import  net.sf.json.JsonConfig;  
  10. import  net.sf.json.processors.JsonValueProcessor;  
  11.   
  12.   
  13. /**  
  14.  * @author Lingo  
  15.  * @since 2007-08-02  
  16.  */   
  17. public   class  DateJsonValueProcessor  implements  JsonValueProcessor {  
  18.     public   static   final  String DEFAULT_DATE_PATTERN =  "yyyy-MM-dd" ;  
  19.     private  DateFormat dateFormat;  
  20.   
  21.     /**  
  22.      * 构造方法.  
  23.      *  
  24.      * @param datePattern 日期格式  
  25.      */   
  26.     public  DateJsonValueProcessor(String datePattern) {  
  27.         try  {  
  28.             dateFormat = new  SimpleDateFormat(datePattern);  
  29.         } catch  (Exception ex) {  
  30.             dateFormat = new  SimpleDateFormat(DEFAULT_DATE_PATTERN);  
  31.         }  
  32.     }  
  33.   
  34.     public  Object processArrayValue(Object value, JsonConfig jsonConfig) {  
  35.         return  process(value);  
  36.     }  
  37.   
  38.     public  Object processObjectValue(String key, Object value,  
  39.         JsonConfig jsonConfig) {  
  40.         return  process(value);  
  41.     }  
  42.   
  43.     private  Object process(Object value) {  
  44.         return  dateFormat.format((Date) value);  
  45.     }  
  46. }  
package anni.core.web.json;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import java.util.Date;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;


/**
 * @author Lingo
 * @since 2007-08-02
 */
public class DateJsonValueProcessor implements JsonValueProcessor {
    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
    private DateFormat dateFormat;

    /**
     * 构造方法.
     *
     * @param datePattern 日期格式
     */
    public DateJsonValueProcessor(String datePattern) {
        try {
            dateFormat = new SimpleDateFormat(datePattern);
        } catch (Exception ex) {
            dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
        }
    }

    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return process(value);
    }

    public Object processObjectValue(String key, Object value,
        JsonConfig jsonConfig) {
        return process(value);
    }

    private Object process(Object value) {
        return dateFormat.format((Date) value);
    }
}



然后在bean -> json的时候

Java代码
  1. /**  
  2.  * write.  
  3.  *  
  4.  * @param bean obj  
  5.  * @param writer 输出流  
  6.  * @param excludes 不转换的属性数组  
  7.  * @param datePattern date到string转换的模式  
  8.  * @throws Exception 写入数据可能出现异常  
  9.  */   
  10. public   static   void  write(Object bean, Writer writer,  
  11.     String[] excludes, String datePattern) throws  Exception {  
  12.     JsonConfig jsonConfig = configJson(excludes, datePattern);  
  13.   
  14.     JSON json = JSONSerializer.toJSON(bean, jsonConfig);  
  15.   
  16.     json.write(writer);  
  17. }  
  18.   
  19. /**  
  20.  * 配置json-lib需要的excludes和datePattern.  
  21.  *  
  22.  * @param excludes 不需要转换的属性数组  
  23.  * @param datePattern 日期转换模式  
  24.  * @return JsonConfig 根据excludes和dataPattern生成的jsonConfig,用于write  
  25.  */   
  26. public   static  JsonConfig configJson(String[] excludes,  
  27.     String datePattern) {  
  28.     JsonConfig jsonConfig = new  JsonConfig();  
  29.     jsonConfig.setExcludes(excludes);  
  30.     jsonConfig.setIgnoreDefaultExcludes(false );  
  31.     jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);  
  32.     jsonConfig.registerJsonValueProcessor(Date.class ,  
  33.         new  DateJsonValueProcessor(datePattern));  
  34.   
  35.     return  jsonConfig;  

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