skip to Main Content

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


  1. You can use Jackson to parse the JSON file into a JsonNode, grab the phoneNumbers field and iterate through the nodes. Jackson uses a LinkedHashMap under the hood, so they original order of they keys should be preserved.

    import java.io.*;
    import java.util.Iterator;
    import java.util.Map.Entry;
    import com.fasterxml.jackson.core.exc.StreamReadException;
    import com.fasterxml.jackson.databind.*;
    
    public class JsonReaderExample {
        private static ObjectMapper objectMapper = new ObjectMapper();
    
        public static void main(String[] args) {
            try {
                ClassLoader classLoader = JsonReaderExample.class.getClassLoader();
                InputStream inputStream = classLoader.getResourceAsStream("input.json");
                JsonNode person = objectMapper.readTree(inputStream);
                JsonNode phoneNumbers = person.get("phoneNumbers");
                if (phoneNumbers.isArray()) {
                    for (final JsonNode phoneNumber : phoneNumbers) {
                        Iterator<Entry<String, JsonNode>> it = phoneNumber.fields();
                        while (it.hasNext()) {
                            Entry<String, JsonNode> entry = it.next();
                            System.out.printf("%s: %s%n", entry.getKey(), entry.getValue());
                        }
                    }
                }
            } catch (StreamReadException e) {
                e.printStackTrace();
            } catch (DatabindException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    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.

    import java.io.*;
    import com.fasterxml.jackson.core.exc.StreamReadException;
    import com.fasterxml.jackson.databind.*;
    
    public class JsonReaderExample {
        private static ObjectMapper objectMapper = new ObjectMapper();
    
        public static void main(String[] args) {
            try {
                ClassLoader classLoader = JsonReaderExample.class.getClassLoader();
                InputStream inputStream = classLoader.getResourceAsStream("input.json");
                Person person = objectMapper.readValue(inputStream, Person.class);
    
                for (PhoneNumber phoneNumber : person.phoneNumbers) {
                    System.out.printf("type: %s%n", phoneNumber.type);
                    System.out.printf("number: %s%n", phoneNumber.number);
                }
            } catch (StreamReadException e) {
                e.printStackTrace();
            } catch (DatabindException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        private static class Person {
            public String firstName;
            public String lastName;
            public Address address;
            public int age;
            public PhoneNumber[] phoneNumbers;
        }
    
        private static class PhoneNumber {
            public String type;
            public String number;
        }
    
        private static class Address {
            public String streetAddress;
            public String city;
            public String state;
            public int postalCode;
        }
    }
    

    Output:

    type: personal
    number: #######23
    type: office
    number: ########
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search