Reputation: 219
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?
Upvotes: 1
Views: 8261
Reputation: 919
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");
Upvotes: 2
Reputation: 1775
request.getJSONObject("result").get("parameters").getString("zip_code")
will solve your problem. JSON objects are built to handle nesting.
Upvotes: 0