如何在java中获取JSON数据

时间:2014-05-22 13:35:28

标签: java json

我有一个JSON字符串:

[
    {
        "customer": {
            "created_at": "2014-05-22T18:24:55+05:30",
            "cust_identifier": null,
            "description": null,
            "domains": null,
            "id": 1000170724,
            "name": "freshdesk",
            "note": null,
            "sla_policy_id": 1000042749,
            "updated_at": "2014-05-22T18:24:55+05:30"
        }
    }
]

如何使用java获取 id 的值?

2 个答案:

答案 0 :(得分:3)

使用JSONObject和JSONArray

int id = new JSONArray(my_json_string).getJSONObject(0).getJSONObject("customer").getInteger("id");

有关JSON in Java的更多信息:http://www.json.org/java/

答案 1 :(得分:0)

您可以使用Google Gson

这是一个小例子:

Gson gson = new Gson();
int id;

try {
    // read file
    FileInputStream input = new FileInputStream("cutomer.json");
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));

    // read file as JSON Object
    JsonObject json = gson.fromJson(reader, JsonObject.class);

    // read attribut "customer" as array
    JsonArray customers = json.getAsJsonArray("customer");

    JsonObject cutomer= customers.get(0).getAsJsonObject();

    // Attribute ausgeben z.B.: name, alter und hobbies
    id = customer.get("is").getAsInt());

} catch (FileNotFoundException e) {
    e.printStackTrace();
}