Json 生成与解析
JsON常用与服务器进行数据交互,JsON中“{}”表示JsONObject,“[]”表示JsONArray
如下Json数据:
1 {"singers":[2 {"ID":"02","name":"tom","gender":"男","tel":["123456","789012"]},3 {"ID":"03","name":"jerry","tel":["899999","666666"]},4 {"ID":"04","name":"jim","tel":["7777","5555"]},{"ID":"05","name":"lily","gender":"女","tel":["222222","111111"]}5 ]}
生成Json数据代码:
public String buildJson() throws JsONException { JsONObject persons = new JsONObject(); JsONArray personArr = new JsONArray(); JsONObject person = new JsONObject(); person.put("ID","02"); person.put("name","tom"); person.put("gender","男"); JsONArray tel = new JsONArray(); tel.put("123456"); tel.put("789012"); person.put("tel",tel); personArr.put(person); JsONObject person2 = new JsONObject(); person2.put("ID","03"); person2.put("name","jerry"); person2.put("gender","男"); JsONArray tel2 = new JsONArray(); tel2.put("899999"); tel2.put("666666"); person2.put("tel",tel2); personArr.put(person2); JsONObject person3 = new JsONObject(); person3.put("ID","04"); person3.put("name","jim"); person3.put("gender","男"); JsONArray tel3 = new JsONArray(); tel3.put("7777"); tel3.put("5555"); person3.put("tel",tel3); personArr.put(person3); JsONObject person4 = new JsONObject(); person4.put("ID","05"); person4.put("name","lily"); person4.put("gender","女"); JsONArray tel4 = new JsONArray(); tel4.put("222222"); tel4.put("111111"); person4.put("tel",tel4); personArr.put(person4); persons.put("singers",personArr); return persons.toString(); }
解析Json数据代码:
private voID parseJsonMulti(String strResult) { try { JsONArray JsonObJs = new JsONObject(strResult).getJsONArray("singers"); String s = ""; for (int i = 0; i < JsonObJs.length(); i++) { JsONObject JsonObj = ((JsONObject) JsonObJs.opt(i)); int ID = JsonObj.getInt("ID"); String name = JsonObj.getString("name"); String gender = JsonObj.getString("gender"); s += "ID号" + ID + ",姓名:" + name + ",性别:" + gender + ",电话:"; JsONArray tel = JsonObj.getJsONArray("tel"); for (int j = 0; j < tel.length(); j++) { s += tel.getString(j)+"/"; } s += "\n"; } tv.setText(s); } catch (JsONException e) { e.printstacktrace(); } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
总结以上是内存溢出为你收集整理的Json 生成与解析详解及实例代码全部内容,希望文章能够帮你解决Json 生成与解析详解及实例代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)