javaJSONObject对象序列化与反序列化
⾸先需要导⼊⼀下包
1.将java对象转换为json字符串(序列化)
先将java对象转换为json对象,在将json对象转换为json字符串
JSONObject json = JSONObject.fromObject(obj);//将java对象转换为json对象
String str = String();//将json对象转换为字符串
2.将json字符串转换为java对象(反序列化)
同样先将json字符串转换为json对象,再将json对象转换为java对象,如下所⽰。
JSONObject obj = new JSONObject().fromObject(jsonStr);  //将json字符串转换为json对象,jsonStr为⼀个json字符串
将json对象转换为java对象(Person为实例类)
Person jb = (Bean(obj,Person.class);//将建json对象转换为Person对象
注:反序列化时可能会遇到以下问题
JSONObject object = JSONObject.fromObject(user);
Object dep = ("department");  //get可获取某个节点的值
object.element("test","test")  //element可添加任意⼀个节点
问题1:时间格式转换出错⼀般时间如("2016-02-16", "01/02/2016"或者其它),可⽤以下⽅法设置
问题3:抽象类(abstract)是⽆法反序列化的,这时你得先取出该对象,然后再移除,最后使⽤⼦类转换
<span >
JSONObject object = JSONObject.Info());
Object assetsObject = ("baseinfo");
JSONObject assetsJson = JSONObject.fromObject(assetsObject);
//防⽌Date为""时反序列化出错
if(StringUtil.isNull(String.("firstDate")))){
}
if(StringUtil.isNull(String.("storeDate")))){
}
Object expands = ("expands");
Object currentCycle = ("currentCycle");  //currentCycle为抽象类,不能反序列化
Map classMap = new HashMap();
classMap.put("expands", Set.class);  //如果该对象为Set、Map等,则在这⾥声明
Assets assets = (Assets) Bean(assetsJson, Assets.class, classMap);
JSONObject cycleJson = JSONObject.fromObject(currentCycle);
Cycle cycle;</span>
<span > //由于⽗类为抽象类,这⾥使⽤⼦类进⾏转化 Assets().getCurrentCycle() instanceof CyclePart){
cycle = (CyclePart) Bean(cycleJson, CyclePart.class);
}else Assets().getCurrentCycle() instanceof CycleCar){
cycle = (CycleCar) Bean(cycleJson, CycleCar.class);
}else{
cycle = (CycleDevice) Bean(cycleJson, CycleDevice.class);
}
assets.setCurrentCycle(cycle);
checkList.setAssets(assets);</span>
<span >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());
object to4. 数组转换成json代码
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
5. ⼀般数据转换成json代码
JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );</span>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。