Suppose we have a block of JAVA code which is iterating through the JSON file.
JAVAfile
// getting phoneNumbers
JSONArray ja = (JSONArray) jo.get("phoneNumbers");//jo is the JSONObject of the given JSON
//Iterating through phonenumbers
Iterator itr2 = ja.iterator();
while (itr2.hasNext())
{
Iterator<Map.Entry>itr1 = ((Map)itr2.next()).entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
JSONfile
{
"firstName": "Souvik",
"lastName": "Dey",
"address": {
"streetAddress": "D P Rd",
"city": "Barasat",
"state": "WB",
"postalCode": 700126
},
"age": 23,
"phoneNumbers": [
{
"type": "personal",
"number": "#######23"
},
{
"type": "office",
"number": "########"
}
]
}
Question
Why am I getting this:
Output
number : #######23
type : personal
number : ########
type : office
Expectations
type : personal
number : #######23
type : office
number : ########
2
Answers
You can use Jackson to parse the JSON file into a
JsonNode
, grab thephoneNumbers
field and iterate through the nodes. Jackson uses aLinkedHashMap
under the hood, so they original order of they keys should be preserved.Your safest bet would be to deserialize the JSON as a POJO. You can use Jackson to read the JSON data and parse it into a
Person
.Output:
Map elements in JSON are not regarded as ordered data. It comes out in a different order for reasons similar to the ordering of a HashMap’s contents. You shouldn’t expect a HashMap to iterate in the same order that you put content into it, and the same is true for mapped content from a JSON source.
If you want to preserve the order of mapped data in JSON, then you should transform the mapped data to an array and store that in JSON.