json lib学习笔记

      json-lib需要的jar包

  • 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
public class App {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		App app=new App();
		//app.arrOrList2JsonArr();
		//app.Map2Json();
		app.Bean2Json();

	}
	/**
	 * Java数组或集合转换成Json数组
	 */
	public void arrOrList2JsonArr(){
		String[] str=new String []{"123","456","789"};
		JSONArray jo=JSONArray.fromObject(str);
		System.out.println(jo);
		List list = new ArrayList();  
		list.add( "first" );  
		list.add( "second" );  
		JSONArray jsonArray = JSONArray.fromObject( list );  
		System.out.println( jsonArray );
		JSONArray jsonArray2 = JSONArray.fromObject( "['json','is','easy']" );  
		System.out.println( jsonArray2 );  ;  
	}
	/**
	 * 把MAP映射成JSON
	 */
	public void Map2Json(){
		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 );  
	}
	/**
	 * 把Bean映射成JSON
	 */
	public void Bean2Json(){
		JSONObject jsonObject = JSONObject.fromObject( new MyBean() );  
		System.out.println( jsonObject );  
	}
	/**
	 * 把Json映射成Bean
	 */
	public void Json2Bean(){
		String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";  
		JSONObject jsonObject = JSONObject.fromObject( json );  
		Object bean = JSONObject.toBean( jsonObject );  
	}

}

 

public 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];");
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPojoId() {
		return pojoId;
	}
	public void setPojoId(int pojoId) {
		this.pojoId = pojoId;
	}
	public char[] getOptions() {
		return options;
	}
	public void setOptions(char[] options) {
		this.options = options;
	}
	public String getFunc1() {
		return func1;
	}
	public void setFunc1(String func1) {
		this.func1 = func1;
	}
	public JSONFunction getFunc2() {
		return func2;
	}
	public void setFunc2(JSONFunction func2) {
		this.func2 = func2;
	} 
	   
	  
}

 

 慧质兰欣

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