JSON Java 分析

JSON 是什么?

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

JSON 的优势?

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

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 解析网站

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();
        }

    }
}

相关文章