0

I am looking for a better (better than what I am doing at the moment) way to extract some data out of a JSON file using Gson. Apparently, the desired data is partly but quite interleaved, something like this:

{
    "media": {
        "content": [
            {
                "node": { "text": "foo", "id": "123", "user": "somebody" }
            }
        ]
    },
    "enabled": true,
    "count": 0,
    "token": "abc"

}

I know I could do something like this, but the approach is quite tedious:

GsonBuilder builder = new GsonBuilder();
jsonObject = builder.create().fromJson(jsonString, jsonObject.class);

class jsonObject {
    Media media;
    Boolean enabled;
    Integer count;
    String token;

    class Media {
        ArrayList<Node> content;
    }

    class Node {
        HashMap<String,String> node;
    }

}

So my question is if there exists a more elegant way to extract the fields? I would like to have a class like:

class jsonObject {
    HashMap<String, String> node;
    Boolean enabled;
    Integer count;
    String token;
}

Thank you very much. Any help and suggestions are appreciated.

Chinmay jain
  • 979
  • 1
  • 9
  • 20
TheDude
  • 168
  • 10
  • I believe this issue is the same as yours https://stackoverflow.com/questions/2779251/how-can-i-convert-json-to-a-hashmap-using-gson – Luca Aug 03 '17 at 15:04
  • Thanks @Luca. This looks interesting, but at first sight not quite what I was looking for. But I will have a closer look. – TheDude Aug 03 '17 at 15:10

1 Answers1

1

That looks like the way to do it. If you were working from a JSON schema file and you ran it thru a generator like http://www.jsonschema2pojo.org/ it would spit out pojos similar to what you have listed, which are perfect for ingesting using GSON.

However, if you want to pull an entire json object into a map you can using

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson("{'key1':'value1','key2':'value2'}", type);
pfranza
  • 3,292
  • 2
  • 21
  • 34
  • Thanks. Ok, maybe I will just have to go through the work and wright a class for each json file I want to work with. The link looks quite useful! – TheDude Aug 03 '17 at 15:13
  • If you look at the http://www.jsonschema2pojo.org/ site I referenced, when you change the 'Source Type' to json, it will infer the proper schema from a block of json data. Then you can have it spit out all of the POJOs for that, This is a pretty good way of generating the classes to get you started without having to write them all by hand. – pfranza Aug 03 '17 at 15:20
  • nice example to demonstrate deserialisation json to java key-value mapping. – atiqkhaled Aug 03 '17 at 21:14