AnthonyH
AnthonyH

Reputation: 37

Parsing JSONObject to access ID when there are multiple ID values (Java)

I am obtaining a JSON response from an API that gives me a list of call records formatted as JSON. I want to parse through the data and find the record ID, my trouble is that each JSON record has multiple ID's and I am not sure how to access the correct one. Keep in mind, I do not know the value of the ID is "3461487000073355176" prior to running the request.

This is my code to receive the JSON, I created a JSONObject so I can hopefully store the value.

1.

         Response response = client.newCall(request).execute();
            String responseBody = response.body().string();
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            JsonParser parser = new JsonParser();
            JsonElement je = parser.parse(responseBody);
            String prettyJsonString = gson.toJson(je);
            
            JSONObject json = new JSONObject(prettyJsonString);
            System.out.println("Json = " + json); 

The JSON the ID I need to access has a comment next to it:

  "data": [
    {
      "Owner": {
        "name": "My namen",
        "id": "346148700000017",
        "email": "[email protected]"
      },
      "$state": "save",
      "$process_flow": false,
      "Street": "95## ### ######",
      "id": "**3461487000073355176**", ----This is the ID I need -----
      "Coverage_A_Dwelling": 100000,
      "$approval": {
        "delegate": false,
        "approve": false,
        "reject": false,
        "resubmit": false
      },
      "Created_Time": "2020-12-10T09:05:17-05:00",
      "Property_Details": "Primary Residence",
      "Created_By": {
        "name": "My name",
        "id": "346148700000017",
        "email": "[email protected]"
      },
      "Description": "Created on Jangl: https://jan.gl/crwp773ytg8",
      "$review_process": {
        "approve": false,
        "reject": false,
        "resubmit": false
      },
      "Property_State": "FL",
      "Property_Street": "95",
      "Roof_Material": "Asphalt Shingle",
      "Full_Name": "Clare Em",
      "Property_City": "Land ",
      "Email_Opt_Out": false,
      "Lead_I_D": "4FFEC0C5-FBA1-2463-DB9B-C38",
      "Insured_1_DOB": "1942-02-20",
      "$orchestration": false,
      "Tag": [],
      "Email": "[email protected]",
      "$currency_symbol": "$",
      "$converted": false,
      "Zip_Code": "338",
      "$approved": true,
      "$editable": true,
      "City": "Land O Lakes",
      "State": "FL",
      "Structure_Type": "Single Family",
      "Prior_Carrier": {
        "name": "Default Carrier (DO NOT DELETE OR CHANGE)",
        "id": "3461487000000235093"
      },
      "Source": {
        "name": "EverQ",
        "id": "346148700006474"
      },
      "First_Name": "Clarence",
      "Modified_By": {
        "name": "My name",
        "id": "3461487000000172021",
        "email": "[email protected]"
      },
      "Phone": "7036159075",
      "Modified_Time": "2020-12-10T09:05:17-05:00",
      "$converted_detail": {},
      "Last_Name": "####",
      "$in_merge": false,
      "$approval_state": "approved",
      "Property_Zip": "34638"
    }
  ],
  "info": {
    "per_page": 200,
    "count": 1,
    "page": 1,
    "more_records": false
  }
}

Upvotes: 0

Views: 2114

Answers (3)

pirho
pirho

Reputation: 12235

Not sure if understood correctly but if you need to get all the IDs in that "level" why don't you try to model it as a class instead of using parser and let Gson do the parsing (this class might be useful later if you need to add more details)?

For example, defining something like this:

@Getter @Setter
// This models the response string from body
public class Response {
    @Getter @Setter
    // This models objects in the data list/array
    public static class IdHolder {
        // Only id because not interested of the rest
        private String id;
    }
    // Only list of id holders because not interested of the rest
    private List<IdHolder> data;
}

Then it would be as easy as:

Response res = gson.fromJson(responseBody, Response.class);
// Print out what you got
res.getData().stream().map(IdHolder::getId).forEach(System.out::println);

Upvotes: 1

geocodezip
geocodezip

Reputation: 161384

The posted JSON response is missing the initial "{".

Your JSON contains data, which is a JSONArray of Owner objects. To get the id field of the first owner (array element 0):

// existing code
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);

// get the id field
JSONArray dataArray = (JSONArray)json.get("data");
JSONObject data0 = (JSONObject) dataArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
System.out.println(id);

Upvotes: 1

Suraj Gautam
Suraj Gautam

Reputation: 1590

If I understood it correctly, you can get the id like this:

Here, json has the following value.

[
{
  "Owner": {
    "name": "My namen",
    "id": "346148700000017",
    "email": "[email protected]"
  }, 
"id": "**3461487000073355176**"
...
}
]

Now I can iterate over JSONArray to get the id.

JSONArray jsonArray = new JSONArray(json);
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
        String id = (String) jsonObject.get("id");
        System.out.println(id);
    }

It prints out **3461487000073355176**.

You can do jsonObject.getJSONArray("data"); in your example to obtain JSON array.

Upvotes: 1

Related Questions