首页 > 解决方案 > 使用 Java 解析 JSON 响应

问题描述

如何使用 Java 解析这个 json 响应

{
    "Name": {
        "name_description": "NIL",
        "date": "NIL"
    },
    "Age": {},
    "City": {},
    "SOAP": [
        ["content", "subtopic", "topic", "code"],
        ["I advised her to call 911, which he did.", "history of present illness", "subjective", "{}"]
    ]
}

标签: javajson

解决方案


使用一个名为 org.json 的库,它确实是最好的 java json 库。

例如:

import org.json.JSONObject;

private static void createJSON(boolean prettyPrint) {    
   JSONObject tomJsonObj = new JSONObject();
   tomJsonObj.put("name", "Tom");
   tomJsonObj.put("birthday", "1940-02-10");
   tomJsonObj.put("age", 76);
   tomJsonObj.put("married", false);

// Cannot set null directly
tomJsonObj.put("car", JSONObject.NULL);

tomJsonObj.put("favorite_foods", new String[] { "cookie", "fish", "chips" });

// {"id": 100001, "nationality", "American"}
JSONObject passportJsonObj = new JSONObject();
passportJsonObj.put("id", 100001);
passportJsonObj.put("nationality", "American");
// Value of a key is a JSONObject
tomJsonObj.put("passport", passportJsonObj);

if (prettyPrint) {
    // With four indent spaces
    System.out.println(tomJsonObj.toString(4));
} else {
    System.out.println(tomJsonObj.toString());
}

}


推荐阅读