0

I have the following JSON string and I am trying to parse it using Google gson. I have tried multiple options but not able to map it into java pojo.

JSON String:

[ 
  {
    DRIVER:  {
               "name" : "Tom",
                "age" : 23
             }
  },
  {
     DRIVER :
      {
         "name" : "Dick",
          "age" : 25
      }
  }
]

Can anyone please help in guiding me on how to parse this kind of a json string. I am stuck at the point when each JsonObject in the JsonArray contains a linkedhashmap.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
som6233
  • 47
  • 6
  • whats the relation to the date though? – Suraj Rao Feb 14 '18 at 13:25
  • Where is map or LinkedHashMap here? I see only json only list with objects? If this is list, easiest way to make wrap entity, like this: class DriverWrap { List drivers; } Yes, it's not good decision, but helps you fast – IvanSPb Feb 14 '18 at 13:28

1 Answers1

0

You need Wrapper classes to map that data into. Following is a working code according to your provided JSON.

 public static void main(String[] args) {
        String json = "YOUR JSON STRING"
        Gson gson = new Gson();
        DataWrap[] data = gson.fromJson(json, DataWrap[].class);
        System.out.println(data[0].getDRIVER().getAge());

    }


    public static class DataWrap {

        private Driver DRIVER;

        public Driver getDRIVER() {
            return DRIVER;
        }

        public void setDRIVER(Driver DRIVER) {
            this.DRIVER = DRIVER;
        }
    }

    public static class Driver {
        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
Sandeep Singh
  • 745
  • 4
  • 20