荟萃馆

位置:首页 > 设计 > 网页设计

Json的生成与解析

JSON常用与服务器进行数据交互,JSON中“{}”表示JSONObject,“[]”表示JSONArray

Json的生成与解析

如下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(); ("id", "02"); ("name", "tom"); ("gender", "男"); JSONArray tel = new JSONArray(); ("123456"); ("789012"); ("tel", tel); (person); JSONObject person2 = new JSONObject(); ("id", "03"); ("name", "jerry"); ("gender", "男"); JSONArray tel2 = new JSONArray(); ("899999"); ("666666"); ("tel", tel2); (person2); JSONObject person3 = new JSONObject(); ("id", "04"); ("name", "jim"); ("gender", "男"); JSONArray tel3 = new JSONArray(); ("7777"); ("5555"); ("tel", tel3); (person3); JSONObject person4 = new JSONObject(); ("id", "05"); ("name", "lily"); ("gender", "女"); JSONArray tel4 = new JSONArray(); ("222222"); ("111111"); ("tel", tel4); (person4); ("singers", personArr); return ring(); }

解析json数据代码:

private void parseJsonMulti(String strResult) { try { JSONArray jsonObjs = new JSONObject(strResult)SONArray("singers"); String s = ""; for (int i = 0; i < th(); i++) { JSONObject jsonObj = ((JSONObject) (i)); int id = nt("id"); String name = tring("name"); String gender = tring("gender"); s += "ID号" + id + ", 姓名:" + name + ",性别:" + gender + ",电话:"; JSONArray tel = SONArray("tel"); for (int j = 0; j < th(); j++) { s += tring(j)+"/"; } s += "n"; } ext(s); } catch (JSONException e) { tStackTrace(); } }

标签:JSON 解析