如何解析java中json对象内的json对象

时间:2017-07-21 23:04:29

标签: java arrays json

我正在尝试解析JSON以下并寻找“zip-code”值“526262”。我是Java的新手并且很难获得邮政编码的价值吗?

这是我的JSON:

{
    "id": "6fffdfdf-8d04-4f4e-b746-20930671bd9c",
    "timestamp": "2017-07-21T03:51:27.329Z",
    "lang": "en",
    "result": {
        "source": "testsrc",
        "resolvedQuery": "testquery",
        "action": "test",
        "actionIncomplete": true,
        "parameters": {
            "zip-code": "526262"
        }
    }
}

这是我的Java代码:

       String test= "{\n" +
            "\t\"id\": \"6fffdfdf-8d04-4f4e-b746-20930671bd9c\",\n" +
            "\t\"timestamp\": \"2017-07-21T03:51:27.329Z\",\n" +
            "\t\"lang\": \"en\",\n" +
            "\t\"result\": {\n" +
            "\t\t\"source\": \"testsrc\",\n" +
            "\t\t\"resolvedQuery\": \"testquery\",\n" +
            "\t\t\"action\": \"test\",\n" +
            "\t\t\"actionIncomplete\": true,\n" +
            "\t\t\"parameters\": {\n" +
            "\t\t\t\"zip-code\": \"526262\"\n" +
            "\t\t}\n" +
            "\t}\n" +
            "}";

JSONObject request = new JSONObject(test);
String zipCode = request.getJSONObject("result").get("parameters").toString();
System.out.println("zipCode is : " + zipCode);

但是我的输出低于输出:

zipCode is : {"zip-code":"526262"}

如何单独获取邮政编码价值?

有人可以帮助如何在java中获取此值吗?

2 个答案:

答案 0 :(得分:1)

获取parameters时应该使用getJSONObject,以便继续使用JSONObject API深入挖掘。

request.getJSONObject("result").getJSONObject("parameters").getString("zip-code");

答案 1 :(得分:0)

request.getJSONObject("result").get("parameters").getString("zip_code")

将解决您的问题。构建JSON对象以处理嵌套。