android中将复杂json对象进行数据转换

来源:互联网 发布:mac tags怎么用 编辑:程序博客网 时间:2024/06/10 23:24

首先大家需要知道的是android集成了apache client和json处理相关的函数,大家可直接调用


1、一般的json对象服务器端都会进行封装成比较简单的基础pojo,但是有些时候我们会在基础的POJO中内部创建私有对象属性例如如下状况,我省略了get和set方法了

public class WugeVO implements Serializable{private double score;//相关基本数据private NameVO nameVO;private SanCaiVO sanCaiVO;//天格数理private ShuliVO tiangeShuli;//人格数理private ShuliVO rengeShuli;//地格数理private ShuliVO digeShuli;//外格数理private ShuliVO waigeShuli;//总格数理private ShuliVO zonggeShuli;//变格数理private ShuliVO biangeShuli;//性格的基础属性private String character_jianpi;//性格的详细描述private String character_note;private NameLiuqin nl;//姓名组合private NameInfo nameInfo;public String toString(){String tmp= this.nameVO.toString()+"/r/n"+this.sanCaiVO.toString()+"/r/n"+this.tiangeShuli.toString()+"/r/n"+this.rengeShuli.toString()+"/r/n"+this.digeShuli.toString()+"/r/n"+this.waigeShuli.toString()+"/r/n"+this.zonggeShuli.toString()+"/r/n"+this.biangeShuli.toString()+"/r/n"+this.character_jianpi+"/r/n"+this.character_note+"/r/n"+this.nl.toString()+"/r/n"+this.nameInfo.toString()+"/r/n"+this.score+"/r/n";return tmp;}

2、这个时候如果返回这样一个json对象,处理起来就比较复杂了。核心难度在于并不是简单的key-value形式了。那我们就要充分发挥客户端JSONObject的实力了

(1)、先将json字符串转成json对象:

Json2Name jn=new Json2Name(jsonstr);


(2)、针对json对象进行json数据转换,转成本地对象,这里我贴出几个有代表性的不同深度的json键值如何获得

try {this.score=jsb.getDouble("score");} catch (JSONException e2) {e2.printStackTrace();}try {this.type=jsb.getJSONObject("nameVO").getString("type");} catch (JSONException e1) {e1.printStackTrace();};try {this.xf_ft=jsb.getJSONObject("nameVO").getJSONObject("xfDic").getString("fanti");} catch (JSONException e) {e.printStackTrace();}try {this.xf_ft_bihua=jsb.getJSONObject("nameVO").getJSONObject("xfDic").getInt("ft_bihua");} catch (JSONException e) {e.printStackTrace();}try {this.xf_jixiong=jsb.getJSONObject("nameVO").getJSONObject("xfDic").getString("jixiong");} catch (JSONException e) {e.printStackTrace();}try {this.xf_jt=jsb.getJSONObject("nameVO").getString("xing_first");} catch (JSONException e) {e.printStackTrace();}try {this.xf_jt_bihua=jsb.getJSONObject("nameVO").getJSONObject("xfDic").getInt("bihua");} catch (JSONException e) {e.printStackTrace();};try {this.xf_pinyin=jsb.getJSONObject("nameVO").getJSONObject("xfDic").getString("py");} catch (JSONException e) {e.printStackTrace();};try {this.xf_wuxing=jsb.getJSONObject("nameVO").getJSONObject("xfDic").getString("jixiong");} catch (JSONException e) {e.printStackTrace();};




原创粉丝点击