'Parse specific JSON object with GSON

I have a JSON file like this:

{
    "header0": "something",
    "header1": "something",
    "header2": "something",
    "data": {
          "value0": "something",
          "value1": "something",
          "value2": "something",
          "value3": "something",
          "value4": "something",
    }
}

How can I parse only the "data" section using Gson? My idea is to read the JSON into a map and then parsing the plain JSON content with my key "data" in GSON. Is there something more elegant I can do?



Solution 1:[1]

Remember - The POJOs in java are useful in defining objects to increase their readability and reusability. If I had to choose, I would go with a POJO class to represent the response, but this is a subjective opinion.

What is POJO?

With POJO:

public class Root {

    public HashMap<String, String> data;
    //getter //setter //constructors
}

        Gson gson = new Gson();
        Root root = gson.fromJson(json, Root.class);
        HashMap<String, String> yourHashMap = root.getData();

Without using POJO(Your approach):

private static final JsonParser jsonParser = new JsonParser();

    public static void main(String[] args) {
        final String json = "<YOUR JSON>";
        final JsonObject rootObject = jsonParser.parse(json).getAsJsonObject();
        HashMap<String, String> yourHashMap = new Gson().fromJson(rootObject.get("data"),
                new TypeToken<HashMap<String, String>>() {
                }.getType());
        System.out.println(yourHashMap);
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1