日期:2014-05-16 浏览次数:20403 次
boolean[] boolArray =newboolean[]{true,false,true}; JSONArray jsonArray1 = JSONArray.fromObject( boolArray ); System.out.println( jsonArray1 ); // prints [true,false,true] List list =newArrayList(); 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"]
Map map =newHashMap(); map.put("name","json"); map.put("bool", Boolean.TRUE ); map.put("int",newInteger(1) ); map.put("arr",newString[]{"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}
/** * Bean.java private String name = "json"; private int pojoId = 1; private char[] ptions = 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(newJsonBean() ); 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]; }}
Java代码 /** * private int row ; private int col ; private String value ; * */ List list =newArrayList(); JsonBean2 jb1 =newJsonBean2(); jb1.setCol(1); jb1.setRow(1); jb1.setValue("xx"); JsonBean2 jb2 =newJsonBean2(); 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}]
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代码 String json ="{\"value\":\"xx\",