JSON 是什么?
JavaScript Object Notation,一种轻量级的数据交换格式
。
JSON 的优势?
易于人阅读和编写,同时也易于机器解析和生成
(一般用于提升网络传输速率)。
JSON 的结构?
键值对
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
数组
{
"people":[
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
{"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
{"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
]
}
例子
{
"programmers": [{
"firstName": "Brett",
"lastName": "McLaughlin",
"email": "aaaa"
}, {
"firstName": "Jason",
"lastName": "Hunter",
"email": "bbbb"
}, {
"firstName": "Elliotte",
"lastName": "Harold",
"email": "cccc"
}],
"authors": [{
"firstName": "Isaac",
"lastName": "Asimov",
"genre": "sciencefiction"
}, {
"firstName": "Tad",
"lastName": "Williams",
"genre": "fantasy"
}, {
"firstName": "Frank",
"lastName": "Peretti",
"genre": "christianfiction"
}],
"musicians": [{
"firstName": "Eric",
"lastName": "Clapton",
"instrument": "guitar"
}, {
"firstName": "Sergei",
"lastName": "Rachmaninoff",
"instrument": "piano"
}]
}
JSON 解析网站
Java 解析 JSON
所需 JAR 包
要使程序可以运行必须引入JSON-lib包——org.json.jar包。综合来看,这个JAR包比较好用。
DEMO
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
String s = "{\"programmers\":[{\"firstName\":\"Brett\",\"lastName\":\"McLaughlin\",\"email\":\"aaaa\"},{\"firstName\":\"Jason\",\"lastName\":\"Hunter\",\"email\":\"bbbb\"},{\"firstName\":\"Elliotte\",\"lastName\":\"Harold\",\"email\":\"cccc\"}]";
JSONObject jsonObject;
JSONArray jsonArray;
try {
jsonObject = new JSONObject(s);
jsonArray = jsonObject.getJSONArray("programmers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject j = (JSONObject) jsonArray.get(i);
System.out.println(j.get("firstName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}