Json 生成与解析详解及实例代码

来源:互联网 发布:c语言编程用什么软件 编辑:程序博客网 时间:2024/05/20 09:10


这篇文章主要介绍了Json 生成与解析详解及实例代码的相关资料,这里附简单实例帮助大家学习理解,需要的朋友可以参考

Json 生成与解析

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

如下json数据:

?
1
2
3
4
5
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]}<br>

生成json数据代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
publicString buildJson() throwsJSONException {
 
    JSONObject persons = newJSONObject();
 
    JSONArray personArr = newJSONArray();
 
    JSONObject person = newJSONObject();
    person.put("id","02");
    person.put("name","tom");
    person.put("gender","男");
 
    JSONArray tel = newJSONArray();
    tel.put("123456");
    tel.put("789012");
 
    person.put("tel", tel);
 
    personArr.put(person);
 
    JSONObject person2 = newJSONObject();
    person2.put("id","03");
    person2.put("name","jerry");
    person2.put("gender","男");
 
    JSONArray tel2 = newJSONArray();
    tel2.put("899999");
    tel2.put("666666");
 
    person2.put("tel", tel2);
 
    personArr.put(person2);
 
 
    JSONObject person3 = newJSONObject();
    person3.put("id","04");
    person3.put("name","jim");
    person3.put("gender","男");
 
    JSONArray tel3 = newJSONArray();
    tel3.put("7777");
    tel3.put("5555");
 
    person3.put("tel", tel3);
 
    personArr.put(person3);
 
 
    JSONObject person4 = newJSONObject();
    person4.put("id","05");
    person4.put("name","lily");
    person4.put("gender","女");
 
    JSONArray tel4 = newJSONArray();
    tel4.put("222222");
    tel4.put("111111");
 
    person4.put("tel", tel4);
 
    personArr.put(person4);
 
 
    persons.put("singers", personArr);
 
 
    returnpersons.toString();
  }

解析json数据代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
privatevoid parseJsonMulti(String strResult) {
    try{
      JSONArray jsonObjs = newJSONObject(strResult).getJSONArray("singers");
      String s = "";
 
      for(inti = 0; i < jsonObjs.length(); i++) {
        JSONObject jsonObj = ((JSONObject) jsonObjs.opt(i));
        intid = jsonObj.getInt("id");
        String name = jsonObj.getString("name");
        String gender = jsonObj.getString("gender");
        s += "ID号"+ id + ", 姓名:" + name + ",性别:"+ gender + ",电话:";
        JSONArray tel = jsonObj.getJSONArray("tel");
        for(intj = 0; j < tel.length(); j++) {
 
          s += tel.getString(j)+"/";
        }
 
        s += "\n";
 
      }
      tv.setText(s);
    }catch(JSONException e) {
      e.printStackTrace();
    }
  }
0 0
原创粉丝点击