JSON学习笔记

现在很多开源的项目用来支持json格式的转化http://www.json.org/java/上有详细的介绍

 

我选择了其中的一个JSON-lib作为json格式转化工具http://json-lib.sourceforge.net/

JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.

 
用这个工具包还需要依赖

  • jakarta commons-lang 2.4
  • jakarta commons-beanutils 1.7.0
  • jakarta commons-collections 3.2
  • jakarta commons-logging 1.1.1
  • ezmorph 1.0.6

1.List to JSON

 

List list = new ArrayList();   
list.add( "first" );   
list.add( "second" );   
JSONArray jsonArray = JSONArray.fromObject( list );   
System.out.println( jsonArray );   
// prints ["first","second"]  

 

2.JSON to List

 

JSONArray jsonArray = JSONArray.fromObject( "["first","second"]" );   
System.out.println( jsonArray );   

 

3.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]; }]

 

 4.Bean to JSON

 

class MyBean{   
   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];");   
  
   // getters & setters   
   ...   
}   
  
JSONObject jsonObject = JSONObject.fromObject( new MyBean() );   
System.out.println( jsonObject );   
/* prints  
  {"name":"json","pojoId":1,"options":["a","f"],  
  "func1":function(i){ return this.options[i];},  
  "func2":function(i){ return this.options[i];}}  
*/  

 

 

还有很多例子可以参考

http://json-lib.sourceforge.net/usage.html

 

目前正在学习和整理中记录在这里方便以后查询和分享给大家

 

 

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