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;
	} 
	   
	  
}

 

 慧质兰欣

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值