json解析和生成

来源:互联网 发布:c语言自己写头文件 编辑:程序博客网 时间:2024/04/29 08:10

Json解析和生成

json的解析和生成举例

http://jingyan.baidu.com/article/574c521937c8e06c8d9dc19b.html

json的解析

json

{    "students": [        {            "age": 23,            "name": "luci"        },        {            "age": 25,            "name": "jack"        },        {            "age": 22,            "name": "Kas"        }    ]}

demo

String jsonStr = "{\"students\":[{\"name\":\"luci\",\"age\":23}, {\"name\":\"jack\",\"age\":25}, {\"name\":\"Kas\",\"age\":22}]}";try {    JSONObject obj = new JSONObject(jsonStr);// 生成对象    JSONArray studentsArr = (JSONArray) obj.get("students");// 取得students数组    String name;    int age;    for (int i = 0; i < studentsArr.length(); ++i) {        JSONObject studentObj = (JSONObject) studentsArr.get(i);        name = studentObj.getString("name");        age = studentObj.getInt("age");        Log.d("ziru", "name = " + name + "," + "age = " + age);    }} catch (JSONException e) {    e.printStackTrace();}

json的生成

json

{    "students": [        {            "age": 23,            "name": "luci"        },        {            "age": 25,            "name": "jack"        },        {            "age": 22,            "name": "Kas"        }    ]}

demo

try {    JSONObject student = new JSONObject();    student.put("name", "luci");    student.put("age", 23);    JSONArray students = new JSONArray();    students.put(student);    JSONObject obj = new JSONObject();    obj.put("students", students);    Log.d("ziru", obj.toString());} catch (JSONException e) {    e.printStackTrace();}
0 0
原创粉丝点击