解析json
作者:互联网
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonDemo {
public static void main(String[] args) {
testJson();
}
public static void testJson() {
String jsonString ="{\"aaa\":\"111111\",\"bbb\":222222,\"ccc\":{\"type\":\"log\"},\"ddd\":{\"type1\":\"00001\",\"type2\":\"00002\"},\"eee\":[{\"name\":\"Thomson\",\"age\":25,\"gender\":\"男\"},{\"name\":\"Rose\",\"age\":23,\"gender\":\"女\"}],\"fff\":{\"xxx1\":\"33333\",\"xxx2\":\"44444\",\"xxx3\":\"null\",\"xxx4\":{\"userId\":\"dss78fds8fds76fds6sd78fds\"},\"xxx5\":{\"code\":\"55555\",\"msg\":{\"yyy1\":\"6666\",\"yyy2\":\"7777\",\"yyy3\":\"888\"}}}}\n";
JSONObject jsonObject = JSONObject.fromObject(jsonString);
//提取出aaa
String aaa = jsonObject.getString("aaa");
System.out.println("aaa:" + aaa);
//提取出bbb
String bbb = jsonObject.getString("bbb");
System.out.println("bbb:" + bbb);
**//注意:此处有嵌套json,应该先将其转换成JSONObject再对其进行操作**
String cccJson = jsonObject.getString("ccc");
JSONObject ccc = JSONObject.fromObject(cccJson);
//提取出type
String type = ccc.getString("type");
System.out.println("type:" + type);
String dddJson = jsonObject.getString("ddd");
JSONObject ddd = JSONObject.fromObject(dddJson);
//提取出type1
String type1 = ddd.getString("type1");
System.out.println("type1:" + type1);
//提取出type2
String type2 = ddd.getString("type2");
System.out.println("type2:" + type2);
**//注意:此处有json的嵌套集合,应先转换成JSONArray再对其进行遍历操作**
JSONArray eee = jsonObject.getJSONArray("eee");
System.out.println(eee.size());
for (int i = 0; i < eee.size(); i++) {
String name = eee.getJSONObject(i).getString("name");
String age = eee.getJSONObject(i).getString("age");
String gender = eee.getJSONObject(i).getString("gender");
System.out.println("name--age--gender:"+name+"--"+age+"--"+gender);
}
**//注意:此处有多重嵌套json,应该先将其转换成JSONObject再对其内部数据分析,不同类型用不同的方法**
String fffJson = jsonObject.getString("fff");
JSONObject fff = JSONObject.fromObject(fffJson);
//直接获取内部msg对应的信息
String xxx5Json = fff.getString("xxx5");
JSONObject xxx5 = JSONObject.fromObject(xxx5Json);
String msgJson = xxx5.getString("msg");
JSONObject msg = JSONObject.fromObject(msgJson);
System.out.println(msg);
String yyy1 = msg.getString("yyy1");
String yyy2 = msg.getString("yyy2");
String yyy3 = msg.getString("yyy3");
System.out.println("yyy1:" + yyy1);
System.out.println("yyy2:" + yyy2);
System.out.println("yyy3:" + yyy3);
}
}
运行结果:
aaa:111111 bbb:222222 type:log type1:00001 type2:00002 2 name–age–gender:Thomson–25–男 name–age–gender:Rose–23–女 {“yyy1”:“6666”,“yyy2”:“7777”,“yyy3”:“888”} yyy1:6666 yyy2:7777 yyy3:888
Process finished with exit code 0
原文链接:https://blog.csdn.net/Thomson617/article/details/84718269
标签:String,getString,JSONObject,System,json,println,解析,out 来源: https://www.cnblogs.com/panghuiwen/p/16502073.html