JSON解析

来源:互联网 发布:ubuntu 16.04下载qq 编辑:程序博客网 时间:2024/04/28 20:08

JSON网络小数据传输,易于阅读和编写
JSON导入包:

1.项目右键——>点击 Build Path——>点击 add External Archives——>包的位置
2.项目右键——>点击 Build Path——>点击 configure Build Path——>Libraries——>add External Archives——>包的位置——>Remove——>ok

  • JSON的创建
    JSONObject obj=new JSONObject();    obj.put("name","张三");    JSONObject obj2=new JSONObject();    obj2.put("name","李四");    JSONObject obj3=new JSONObject();    obj2.put("name","王五");    JSONArray array=new JSONArray();    array.add(obj);    array.add(obj2);    array.add(obj3);    JSONObject clazz=new JSONObject();    clazz.put("clazzname","一年级一班");    clazz.put("num",3);    clazz.put("students",array);    System.out.println(clazz.toString());

运行结果:

{“clazzname”:”一年级一班”,”num”:3,”students”:[{“name”:”张三”},{“name”:”李四”},{“name”:”王五”}]}

  • Json解析
JSONObject json=JSONObject.fromObject(clazz);        System.out.println(clazz.getJSONArray("student").getJSONObject(0));        System.out.println(clazz.getJSONArray("student").getJSONObject(1));        System.out.println(clazz.getJSONArray("student").getJSONObject(2));        System.out.println(clazz.getJSONArray("student").getJSONObject(0).getString("username"));        System.out.println(clazz.getJSONArray("student").getJSONObject(1).getString("username"));        System.out.println(clazz.getJSONArray("student").getJSONObject(2).getString("username"));        System.out.println(clazz.getString("clazzname"));

运行结果

{“username”:”张三”}
{“username”:”李四”}
{“username”:”王五”}
张三
李四
王五
一年级一班

0 0