[关闭]
@Yano 2016-07-16T16:12:26.000000Z 字数 1744 阅读 2545

JSON Java 解析

Java


JSON 是什么?

JavaScript Object Notation,一种轻量级的数据交换格式

JSON 的优势?

易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。

JSON 的结构?

键值对

  1. {"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}

数组

  1. {
  2. "people":[
  3. {"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
  4. {"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
  5. {"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
  6. ]
  7. }

例子

  1. {
  2. "programmers": [{
  3. "firstName": "Brett",
  4. "lastName": "McLaughlin",
  5. "email": "aaaa"
  6. }, {
  7. "firstName": "Jason",
  8. "lastName": "Hunter",
  9. "email": "bbbb"
  10. }, {
  11. "firstName": "Elliotte",
  12. "lastName": "Harold",
  13. "email": "cccc"
  14. }],
  15. "authors": [{
  16. "firstName": "Isaac",
  17. "lastName": "Asimov",
  18. "genre": "sciencefiction"
  19. }, {
  20. "firstName": "Tad",
  21. "lastName": "Williams",
  22. "genre": "fantasy"
  23. }, {
  24. "firstName": "Frank",
  25. "lastName": "Peretti",
  26. "genre": "christianfiction"
  27. }],
  28. "musicians": [{
  29. "firstName": "Eric",
  30. "lastName": "Clapton",
  31. "instrument": "guitar"
  32. }, {
  33. "firstName": "Sergei",
  34. "lastName": "Rachmaninoff",
  35. "instrument": "piano"
  36. }]
  37. }

JSON 解析网站

JSON在线解析及格式化验证

Java 解析 JSON

所需 JAR 包

要使程序可以运行必须引入JSON-lib包——org.json.jar包。综合来看,这个JAR包比较好用。

DEMO

  1. import org.json.JSONArray;
  2. import org.json.JSONException;
  3. import org.json.JSONObject;
  4. public class Test {
  5. public static void main(String[] args) {
  6. String s = "{\"programmers\":[{\"firstName\":\"Brett\",\"lastName\":\"McLaughlin\",\"email\":\"aaaa\"},{\"firstName\":\"Jason\",\"lastName\":\"Hunter\",\"email\":\"bbbb\"},{\"firstName\":\"Elliotte\",\"lastName\":\"Harold\",\"email\":\"cccc\"}]";
  7. JSONObject jsonObject;
  8. JSONArray jsonArray;
  9. try {
  10. jsonObject = new JSONObject(s);
  11. jsonArray = jsonObject.getJSONArray("programmers");
  12. for (int i = 0; i < jsonArray.length(); i++) {
  13. JSONObject j = (JSONObject) jsonArray.get(i);
  14. System.out.println(j.get("firstName"));
  15. }
  16. } catch (JSONException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注