user1882624
user1882624

Reputation: 333

Read single value from nested object using Gson in Java

Below is my Json. I want to get the value of "Id" inside "Details" using Gson

{
    "name": "testAutomation-1",
    "owner": "TestUSer",
    "description": "testAutomation-1",
    "subSet": [
        "test-audit"
    ],
    "labels": "{\"engagementType\":\"Sx\",\"type\":\"collect\"}",
    "createdTime": 1548508294790,
    "updatedTime": 1548654725381,
    "scheduleDateTime": null,
    "timeZone": null,
    "jobStatus": "Report-Requested",
    "loggedInUser": null,
    "Details": [
        {
            "Status": "Completed",
            "Id": "fe1f6b40-216b-11e9-a769-25be4c5889e7"
        }
    ]
}

I created a map using the below code. But not sure how to get the value

Map<String, Object> createmap = new HashMap<String, Object>();
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Object>>(){}.getType();
createmap = gson.fromJson(jsonobj.toString(), type);

Upvotes: 2

Views: 719

Answers (3)

Thibstars
Thibstars

Reputation: 1083

Assuming that you need the first element of the array, you could do something like this (knowing that DATA is the JSon String you provided):

Map<String, JsonElement> resultMap;
Gson gson = new Gson();
Type type = new TypeToken<Map<String, JsonElement>>() {}.getType();
JsonElement jsonElement = gson.fromJson(DATA, JsonElement.class);
resultMap = gson.fromJson(jsonElement.toString(), type);

JsonArray details = resultMap.get("Details").getAsJsonArray();
JsonObject recordElement = details.get(0).getAsJsonObject();
System.out.println(recordElement.get("Id").getAsString());

All this does is fetch the Details array as a JsonArray and it fetches the value of the Id element afterwards.

Since you seem to be dealing with a UUID, you could maybe benefit from using:

UUID uuid = UUID.fromString(recordElement.get("Id").getAsString());

Upvotes: 2

pirho
pirho

Reputation: 12215

In your JSON Details is a list or an array. So there is not just one id in some cases and you should prepare for that also.

It is usually also a good habit to create DTOs to describe data, so like two below classes:

Data

@Getter
public class Data {
    // Recommendation, in Java field name should start lower case
    @SerializedName("Details")
    List<Detail> details; // Could be some List also
}

Detail

@Getter
public class Detail {
    // Recommendation, in Java field name should start lower case
    @SerializedName("Id")
    private UUID id;
}

This also allows later to flexibly pick up any other fields you need from the same JSON.

Serialize your JSON like:

Data data = gson.fromJson(YOUR_JSON, Data.class);

Check the ids - for example - like:

data.getDetails().forEach(d -> log.info("{}", d.getId()));

Upvotes: 0

Anitha.R
Anitha.R

Reputation: 354

As per Gson guide, you need to use the correct parameterized type instead of your generic type. Then you can easily access the value you need from the map.

Map<String, Dummy> map = new HashMap<String, Dummy>();
Type t = new TypeToken<Map<String, Dummy>>() {}.getType();
map = new Gson().fromJson(jsonobj.toString(), type);

Then you can get the map value (map.get("details") and read the id from that.

Upvotes: 0

Related Questions