0

I have different jsons and don't want to create classes for each.

Is there a way to parse entire json file into Map?

For example:

{
"response": [
    {
      "id": 1,
      "first_name": "Pavel",
      "last_name": "Durov",
      "screen_name": "durov",
      "photo_200_orig": "https://pp.vk.me/c625129/v625129631/34d5e/BkAwjDyPg.jpg"
    }
]}

And do like this:

Map map = Gson.fromJson(jsonString, Someclass.class);
long id = map.get("response").get(0).get("id");

Is there a way?

raiym
  • 1,439
  • 1
  • 28
  • 54
  • Possible duplicate of [JSON GSON.fromJson Java Objects](http://stackoverflow.com/questions/5314813/json-gson-fromjson-java-objects) – nafas Jan 19 '16 at 09:28
  • Doesn't it work if you do Map map = Gson.fromJson(jsonString, Map.class);? – uncaught_exception Jan 19 '16 at 09:30
  • no, when `map.get("response")` you're getting String. And you must do fromJson again – raiym Jan 19 '16 at 09:31
  • @nafas yes. But is creating classes the only way? – raiym Jan 19 '16 at 09:32
  • @raiym Interesting I have never used GSON before. With Jackson I often parse deeply nested JSON with a Map and it automatically creates lists of Maps or nested Lists from arrays. – uncaught_exception Jan 19 '16 at 09:36
  • Oh. I will take a look now – raiym Jan 19 '16 at 09:36
  • 1
    It looks like it's doable, but you have to pre-define the depth of nested collections. Look here: http://stackoverflow.com/questions/2779251/how-can-i-convert-json-to-a-hashmap-using-gson – nolexa Jan 19 '16 at 09:37

0 Answers0