JSON Array Of Entries to POJO

374 views Asked by At

I have a JSON file that has multiple entries inside of an array. Each of those entries needs to be mapped to a java object. Here is the JSON string I am testing with (http://jsonlint.com/ validated the JSON below, but I had to erase all of the escape characters which I use in the actual Java test),

  [{
    "LocId":99,
    "typeId":99,
    "name":"foo",
    "parentId":99,
    "geoCode":
    {
      "type":"foo",
      "coordinates":
      [{
        "latitude":99.0,
        "longitude":99.0
      }]
    }
  ,
    "LocId":8,
    "typeId":99,
    "name":"foo",
    "parentId":99,
    "geoCode":
    {
      "type":"foo",
      "coordinates":
      [{
        "latitude":99.0,
        "longitude":99.0
      }]
    }
  }]

I read this string in like this,

    String str = "The JSON string shown above";
    InputStream is = new ByteArrayInputStream(str.getBytes());
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    LocIdClass[] locations = new Gson().fromJson(br, LocIdClass[].class);

But the size of my locations array is always one and only the last entry in the JSON string is stored.

    for(int i=0; i<locations.length; i++)
        System.out.println(locations[i]);

    System.out.println("The size of the array is " + locations.length);

I'm not sure why only the last entry in the JSON string would be retrieved but the others are skipped. I referred to this SO post to figure out the POJO array Jackson - Json to POJO With Multiple Entries.

1

There are 1 answers

3
Derek_M On BEST ANSWER

you have an error in your current json payload, try this:

    [
        {
            "LocId": 99,
            "typeId": 99,
            "name": "foo",
            "parentId": 99,
            "geoCode": {
                "type": "foo",
                "coordinates": [
                    {
                        "latitude": 99,
                        "longitude": 99
                    }
                ]
            }
        },
        {
            "LocId": 8,
            "typeId": 99,
            "name": "foo",
            "parentId": 99,
            "geoCode": {
                "type": "foo",
                "coordinates": [
                    {
                        "latitude": 99,
                        "longitude": 99
                    }
                ]
            }
        }
    ]

Edit: To avoid this issue in the future, you can use jsonlint.com to check your json. Make sure it is what you expect it to be.