JSON解析
程序员文章站
2022-06-05 14:07:28
...
json格式如下
{
"report": {"id": 1,"name": "liu","age": 23,"sex": "男"},
"reportInfo": [
{"id": 1,"name": "liu","age": 23,"sex": "男"},
{"id": 2,"name": "liu","age": 23,"sex": "男"},
{"id": 3,"name": "liu","age": 23,"sex": "男"},
{"id": 4,"name": "liu","age": 23,"sex": "男"}
]
}
导入的jar包
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
代码编写如下
String Value = "{\"report\":{\"id\":\"0\",\"name\":\"hu\",\"age\":\"18\",\"sex\":\"男\"},\"web\":[{\"id\":\"1\",\"name\":\"liu\",\"age\":\"23\",\"sex\":\"女\"},{\"id\":\"2\",\"name\":\"wang\",\"age\":\"20\",\"sex\":\"男\"},{\"id\":\"3\",\"name\":\"li\",\"age\":\"23\",\"sex\":\"女\"},{\"id\":\"4\",\"name\":\"zhang\",\"age\":\"21\",\"sex\":\"男\"}]}";
JSONObject obj = JSONObject.fromObject(Value); //解析JSON字符串
JSONObject report = obj.getJSONObject("report");
String id = (String) report.get("id");
String name = (String) report.get("name");
String age = (String) report.get("age");
String sex = (String) report.get("sex");
System.out.println("id值是:"+id+",name是:"+name+",age是:"+age+",sex是:"+sex);
JSONArray arr = obj.getJSONArray("web");//接收JSON对象里的数组
for (int i = 0; i < arr.size(); i++) {
JSONObject temp = arr.getJSONObject(i);
String ids = (String) temp.get("id");
String names = (String) temp.get("name");
String ages = (String) temp.get("age");
String sexs = (String) temp.get("sex");
System.out.println("ids值是:"+ids+",names是:"+names+",ages是:"+ages+",sexs是:"+sexs);
}
json的格式有很多种,这里主要涉两种:对象、数组包含对象。
JSONObject对象形式,JSONArray数组形式。
欢迎大家一起讨论、学习!
上一篇: 常见的Web安全问题