Json 生成与解析详解及实例代码
程序员文章站
2024-02-29 18:49:04
json 生成与解析
json常用与服务器进行数据交互,json中“{}”表示jsonobject,“[]”表示jsonarray
如下json数据:
1 {...
json 生成与解析
json常用与服务器进行数据交互,json中“{}”表示jsonobject,“[]”表示jsonarray
如下json数据:
1 {"singers":[ 2 {"id":"02","name":"tom","gender":"男","tel":["123456","789012"]}, 3 {"id":"03","name":"jerry","gender":"男","tel":["899999","666666"]}, 4 {"id":"04","name":"jim","gender":"男","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(); } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!