-1

This is the JSON from which I want to fetch value of address. It has JSONObject inside JSONArray

    {
      "user": "user1",
      "Post": "PC",
      "thirdparty": {
        "companyName": "testCompany"
      },
      "Usedata": [
        {
          "data": {
            "place": "india",
            "address": "Mumbai"
          },
          "department": {
            "deptcode": "IT",
            "Location": "Mumbai"
          }
        }
      ]
    }

4 Answers4

1

You can understand this example is so easy

import org.json.*;


JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

 JSONArray arr = obj.getJSONArray("posts");
 for (int i = 0; i < arr.length(); i++)
  {
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
  }
  • @NITISH DASTANE if ur problem will be solved,Please tick this answer –  Sep 06 '17 at 06:06
1

Try below code to get address value from JSON.

JSONObject response=new JSONObject(jsonObjStr);
String address=response.getJSONArray("Usedata").getJSONObject(0).getJSONObject("data").getString("address");
Raju Sharma
  • 2,496
  • 3
  • 23
  • 41
0

There're a lot of ways to deal with it,i suggest you deal with a tool named "JsonPath",the git is https://github.com/json-path/JsonPath.

1、Import dependency to pom.xml like this:

<dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.2.0</version>
   </dependency>

2、Then you can deal with it in a easy way:

public static void main (String args[]){
     String place = getValue("yourjson",$.Usedata[0].data.place);
     String address = getValue("yourjson",$.Usedata[0].data.address );
 }

public static <T> T getValue(String jsonContent, String path) {
    Configuration conf = Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS);
    ReadContext ctx = JsonPath.parse(jsonContent, conf);
    return ctx.read(path);
}
cameron
  • 3
  • 3
0

You can also use the library org.json

They provide the support to opt a value instead of directly using a get. This means that the code will not break even if the key you specify doesn't exist.

String address = "";
JSONObject response = new JSONObject(inputJSONString);
JSONArray userDataArray = response.optJSONArray("Usedata");
if (userDataArray != null && userDataArray.length() > 0) {
    JSONObject dataObject = userDataArray.optJSONObject(0);
    if (dataObject != null && dataObject.has("address")) {
            address = dataObject.getString("address");
    }
}
Chinmay jain
  • 979
  • 1
  • 9
  • 20