Search code examples
javajsonjacksonjson-simple

print values from json file


I'm using the following code to get JSON data from file, currently I was able to achieve the JSON but in one string. I want to parse it to array. The json file is like this:

{
    "employee": [
        {
            "name": "joan",
            "lastname": "test",
            "age": 23
        },

I'm using the following code to get the data but I get it in one string and I want to print some of the data

JSONObject jsonObject = (JSONObject) parser
                .parse(new FileReader("C:\\MockData\\Json\\js.txt"));

        JSONParser parser1 = new JSONParser();
        ContainerFactory containerFactory = new ContainerFactory() {
            public List<?> creatArrayContainer() {
                return new LinkedList<Object>();
            }

            public Map<?, ?> createObjectContainer() {
                return new LinkedHashMap<Object, Object>();
            }

        };

        Map<?, ?> json = (Map<?, ?>) parser1.parse(jsonObject.toJSONString(), containerFactory);

        Iterator<?> iter = json.entrySet().iterator();
        System.out.println("==iterate result==");

        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();

            System.out.println(entry.getKey() + "=>" + entry.getValue());

        }

this is the output

employee=[{age=23, name=joan, lastname=test}, {age=22, name=Alex, lastname=avz}, {age=65, name=Dan, lastname=severn}]

Here the entry.getValue() is retuen one concatenated string of the array, the while is running just one time... but I want to loop on it to take the key value. How should I do that? for example if I want to print name alex witn age 22 how should I do that?

Note: The file can be changed so I don't know the keys (now its name but in can be firstName and any other field for that i need generic solution).

if there is a way to use different parser that can do that Im open.


Solution

  • The following is the full solution to your question. With this code you can break down the data to each employee and also separate the employee attributes.

     Set<String> keySet = jsonObject.keySet();
                    Iterator keySetIterator = keySet.iterator();
                    while(keySetIterator.hasNext()){
                        JSONArray array = (JSONArray)jsonObject.get(keySetIterator.next());
    
                            while(employeeKeySetIterator.hasNext()){
                                String employeeKey = employeeKeySetIterator.next().toString();
                                System.out.println(employeeKey + " : "+ employee.get(employeeKey));
                            }
                        }
                    }