json-lib-2.3-jdk15.jar
commons-beanutils-1.7.0.jar
commons-httpclient-3.1.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
commons-collections-3.1.jar
ezmorph-1.0.6.jar (类型转换用)
这些包可以从一下地方下载:
http://commons.apache.org/index.html
http://json-lib.sourceforge.net/
http://ezmorph.sourceforge.net/
http://www.docjar.com/
先将java对象转换为json对象,在将json对象转换为json字符串
JSONObject json = JSONObject.fromObject(obj);//将java对象转换为json对象
String str = json.toString();//将json对象转换为字符串
<span style="font-family:Microsoft YaHei;font-size:14px;">
JSONObject object = JSONObject.fromObject(checkInfo.getInfo()); Object assetsObject = object.get("baseinfo"); JSONObject assetsJson = JSONObject.fromObject(assetsObject); //防止Date为""时反序列化出错 if(StringUtil.isNull(String.valueOf(assetsJson.get("firstDate")))){ assetsJson.remove("firstDate"); //为空时移除该节点 } if(StringUtil.isNull(String.valueOf(assetsJson.get("storeDate")))){ assetsJson.remove("storeDate"); } Object expands = assetsJson.get("expands"); Object currentCycle = assetsJson.get("currentCycle"); //currentCycle为抽象类,不能反序列化 assetsJson.remove("expands"); assetsJson.remove("currentCycle"); Map classMap = new HashMap(); classMap.put("expands", Set.class); //如果该对象为Set、Map等,则在这里声明 Assets assets = (Assets) JSONObject.toBean(assetsJson, Assets.class, classMap); JSONObject cycleJson = JSONObject.fromObject(currentCycle); Cycle cycle;</span>
<span style="font-family:Microsoft YaHei;font-size:14px;"> //由于父类为抽象类,这里使用子类进行转化 if(checkList.getAssets().getCurrentCycle() instanceof CyclePart){ cycle = (CyclePart) JSONObject.toBean(cycleJson, CyclePart.class); }else if(checkList.getAssets().getCurrentCycle() instanceof CycleCar){ cycle = (CycleCar) JSONObject.toBean(cycleJson, CycleCar.class); }else{ cycle = (CycleDevice) JSONObject.toBean(cycleJson, CycleDevice.class); } assets.setCurrentCycle(cycle); checkList.setAssets(assets);</span>
<span style="font-family:Microsoft YaHei;font-size:14px;">1. List集合转换成json代码 List list = new ArrayList(); list.add( "first" ); list.add( "second" ); JSONArray jsonArray2 = JSONArray.fromObject( list ); 2. Map集合转换成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 json = JSONObject.fromObject(map); 3. Bean转换成json代码 JSONObject jsonObject = JSONObject.fromObject(new JsonBean()); 4. 数组转换成json代码 boolean[] boolArray = new boolean[] { true, false, true }; JSONArray jsonArray1 = JSONArray.fromObject(boolArray); 5. 一般数据转换成json代码 JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );</span>