0

I am trying to parse the content of JSON file text.json by using Jackson library.

What I want is to make a java method in the following code to get all keys and values of it, but so far in my code I get only the first key and the first value of the JSON file.

Here is my Java class:

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonStreamExample {
    public static void main(String[] args) {
        try {
            //Create a JsonFactory instance
            JsonFactory factory = new JsonFactory();

            //Create a JsonParser instance to read from file c:\\text.json
            JsonParser jParser = factory.createJsonParser(new File("c:\\text.json"));

            /*Create an ObjectMapper instance to provide a pointer
             * to root node of the tree after reading the JSON
             */
            ObjectMapper mapper = new ObjectMapper(factory);

            //Create tree from JSON
            JsonNode rootNode = mapper.readTree(jParser);  

            Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.getFields();
            while (fieldsIterator.hasNext()) {
                Map.Entry<String,JsonNode> field = fieldsIterator.next();
                System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
            }

            jParser.close();

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

My Eclipse output is the following which creates only 1 pair(key-value):

Key: cells  Value:[{"type":"basic.Circle","size":{"width":90,"height":54},"position":{"x":-80,"y":200},"angle":0,"id":"cae4c219-c2cd-4a4b-b50c-0f269963ca24","embeds":"","z":1,"wi_name":"START","wi_displayName":"START","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"circle":{"fill":"#000000","width":50,"height":30,"stroke-width":1,"stroke-dasharray":"0"},"text":{"font-size":10,"text":"START","fill":"#ffffff","font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Circle","size":{"width":90,"height":54},"position":{"x":210,"y":200},"angle":0,"id":"d23133e0-e516-4f72-8127-292545d3d479","embeds":"","z":2,"wi_name":"END","wi_displayName":"END","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"circle":{"fill":"#000000","width":50,"height":30,"stroke-width":1,"stroke-dasharray":"0"},"text":{"font-size":10,"text":"END","fill":"#ffffff","font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Rect","position":{"x":-80,"y":370},"size":{"width":90,"height":54},"angle":0,"id":"a53898a5-c018-45c4-bd3f-4ea4d69f58ed","embeds":"","z":3,"wi_name":"ACTIVITY_1","wi_displayName":"ACTIVITY 1","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"rect":{"width":50,"height":30,"rx":2,"ry":2,"stroke-width":1,"stroke-dasharray":"0"},"text":{"text":"Activity","font-size":10,"font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Rect","position":{"x":220,"y":370},"size":{"width":90,"height":54},"angle":0,"id":"e2bd21f2-508d-44b9-9f68-e374d4fa87ea","embeds":"","z":4,"wi_name":"ACTIVITY_2","wi_displayName":"ACTIVITY 2","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"rect":{"width":50,"height":30,"rx":2,"ry":2,"stroke-width":1,"stroke-dasharray":"0"},"text":{"text":"Workitem","font-size":10,"font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"link","source":{"id":"cae4c219-c2cd-4a4b-b50c-0f269963ca24"},"target":{"id":"d23133e0-e516-4f72-8127-292545d3d479"},"router":{"name":"manhattan"},"labels":[{"position":0.5,"attrs":{"text":{"text":"Name"}}}],"id":"60ee7ff7-3a3b-487d-b581-49027e7bebe4","embeds":"","z":5,"attrs":{".marker-source":{"d":"M 10 0 L 0 5 L 10 10 z","transform":"scale(0.001)"},".marker-target":{"d":"M 10 0 L 0 5 L 10 10 z"},".connection":{"stroke":"black"}}},{"type":"link","source":{"id":"a53898a5-c018-45c4-bd3f-4ea4d69f58ed"},"target":{"id":"e2bd21f2-508d-44b9-9f68-e374d4fa87ea"},"router":{"name":"manhattan"},"labels":[{"position":0.5,"attrs":{"text":{"text":"Name"}}}],"id":"cea0d1c2-2c18-4bd7-ba35-d94918c6fc9b","embeds":"","z":6,"attrs":{".marker-source":{"d":"M 10 0 L 0 5 L 10 10 z","transform":"scale(0.001)"},".marker-target":{"d":"M 10 0 L 0 5 L 10 10 z"},".connection":{"stroke":"black"}}}]

How will I do it please?

  • Possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – Rosário Pereira Fernandes Jan 09 '17 at 12:37
  • What do you mean exactly by "all keys and values"? Your JSON example is a hierarchical structure. Could you provide a unit test that describes the behaviour you expect? – Gustave Jan 09 '17 at 12:55
  • I want to be able to traverse all my JSON, inside JSON arrays and objects and get all key-vaue pairs. How will I do it please in my Java class? Do I miss something? – Reputated_Enginius Jan 11 '17 at 15:07

2 Answers2

1

In the above code sample, the nested/Hierarchical Structure is not considered of json value and it directly prints it as field.getValue().

You'll have to check for the type of value using

if(field.getValue().isObject())
{
   parse(field.getValue())
}

The Parse Method could be as follows

private void parse(JsonNode jsonNode)
    {
        Iterator<Map.Entry<String, JsonNode>> fieldsIterator = jsonNode.getFields();
        while (fieldsIterator.hasNext())
        {
            Map.Entry<String, JsonNode> field = fieldsIterator.next();

            if (field.getValue().isObject())
            {
                parse(field.getValue());
            }

            System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
        }
    }

Then you have to just call the parse method for the rootNode.

Kaushik Patel
  • 239
  • 1
  • 5
  • Thank you so much @Kaushik Patel . After using your code how will my final class be? – Reputated_Enginius Jan 11 '17 at 14:04
  • Don't forget that I want to be able to traverse all my JSON, inside JSON arrays and objects and get all key-vaue pairs. How will I do it? – Reputated_Enginius Jan 11 '17 at 15:06
  • Replace your Iterator and While loop with the line parse(field.getValue()) and add parse method as told above – Kaushik Patel Jan 12 '17 at 13:46
  • 1
    To be able to parse inside a Json Array of Json Objects you'll need to check inside a Json Array using the same kind of technique – Kaushik Patel Jan 12 '17 at 13:47
  • Thanks @Kaushik. How many checks do I have to perform e.x. for a JSON that has lots of JSON arrays and JSON objects inside? Can it happen automatically? – Reputated_Enginius Jan 12 '17 at 13:56
  • You have to just write code to check once for all the cases that are applicable for you as we have done here for JsonObject type..... The code should automatically be called depending on the recursion we apply.... I could help you with what checks need to be done if I get a sample JSON you need to parse a complex one that would probably cover all your cases – Kaushik Patel Jan 15 '17 at 12:48
0

I solved my problem by changing JSON library.

I used json-simple-1.1.1

My final code that worked is the following:

package jsontoxml;

import java.io.*;

import org.json.simple.parser.JSONParser;
import org.json.simple.*;
import java.util.*;


public class JacksonStreamExample {

   public static void main(String[] args) {
       JSONParser parser = new JSONParser();
     try {
        Object obj = parser.parse(new FileReader("text.json"));
        JSONObject jsonObject = (JSONObject) obj;

        JSONArray cells = (JSONArray) jsonObject.get("cells");
        Iterator<JSONObject> iterator = cells.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

     } catch (Exception e) {

      e.printStackTrace();

     }

  }

}