1

I'm trying to parse below JSON and looking for "zip-code" value "526262". I'm new to Java and struggling to get the zip-code value?

This is my 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"
        }
    }
}

And this is my Java code:

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

But I'm getting below output:

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

How to get zip-code value alone?

Can someone help how to get this value in java?

1
  • 1
    String zipCode = request.getJSONObject("result").get("parameters").get("zip-code").toString(); ? Commented Jul 21, 2017 at 23:07

2 Answers 2

2

You should use getJSONObject when getting parameters so that you can keep using the JSONObject API to dig deeper.

request.getJSONObject("result").getJSONObject("parameters").getString("zip-code");
Sign up to request clarification or add additional context in comments.

Comments

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

will solve your problem. JSON objects are built to handle nesting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.