-1

I understand that the correct JSON format would be like:

{"coord":[{"lat":37.4056,"lon":-122.0775}]}

But I have a data coming to me in this format

{"coord":{"lat":37.4056,"lon":-122.0775}}

If this is a correct JSON format, how to parse it in Java?

Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185

1 Answers1

1

In Json the {} brackets indicates an object, while the [] ones indicates an array.

Your first example contains an array with one object containing lat and lon properties, the object is accessed by data.coord[0].lat.
Your second example is an object containing a object with lat and lon properties.
That is, no array, just an object. The object is accessed by data.coord.lat.

Both are correct json.

You pretty much parse them the same way, they will just be different types (the object or array under coord).

// Parse:
JSONObject obj = new JSONObject(jsondatastring);
// Fetching the object:
JSONObject coord = obj.getJSONObject("coord");
// Or fetching the array:
JSONArray coords = obj.getJSONArray("coord");
Jite
  • 5,761
  • 2
  • 23
  • 37