banzai
banzai

Reputation: 65

Json parsing: Iterating through the values?

I'm trying to use json.simple to get things from this json file:

"Main": {
    "Part1":{
        "Length": 2,
        "Flags": 2,
        "Sequence": 4
    },
    "Part2":{
        "Length": 2,
        "Type":2,
        "Main_Dest":4,
        "Main_Source":4,
        "Sequence":4,
        "Data": {
            "1":12,
            "2":24
        },
        "Blank": 8
    }
}

Basically, I want to reach the "Type" value in Part2, and on the way add all values. Meaning in the end I want to have the sum 10 (length+flags+sequence+length) and the number 2 for the value "Type". My main problem here is that I have to do it generically, so I can't just collect the values by name because they might change or additional values could be added. Only the value "Type" will always be called exactly that.

What I've done so far is this:

private static void parseJson() {
    String path = "...config.json";
    boolean count = false;
    int sum = 0;
    try {
        FileReader reader = new FileReader(path);
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
        jsonObject.entrySet();
        JSONObject main = (JSONObject) jsonObject.get("Main");
        for (Iterator iterator = main.keySet().iterator(); iterator.hasNext();){
            String key = (String) iterator.next();

            //this is where I'm stumped. Do I keep going into the JSONObject until I get to a value?

            if (count){
                sum += (int) sahara.get(key);
            }
            if (key.equals("Type")){
                count = true;
            }

        }
        System.out.println(skip);
    } catch (Exception e) {

    }

}

Obviously I don't really know what I'm doing with this. How do I iterate the lowest level in the json file?

As a little side question, which Json parser libraries should I use if I might sell my software? In other words, which doesn't cause licensing issues?

Upvotes: 0

Views: 359

Answers (2)

ceving
ceving

Reputation: 23846

Use the stream API for Json.

I have added the missing curly braces to fix your input.

{
  "Main": {
    "Part1":{
      "Length": 2,
      "Flags": 2,
    "Sequence": 4
    },
    "Part2":{
      "Length": 2,
      "Type":2,
      "Main_Dest":4,
      "Main_Source":4,
      "Sequence":4,
      "Data": {
        "1":12,
        "2":24
      },
      "Blank": 8
    }
  }
}

This examples shows how to use the stream API.

// -*- compile-command: "javac -cp javax.json-1.0.jar q43737601.java && java -cp .:javax.json-1.0.jar q43737601"; -*-

import java.io.FileReader;
import javax.json.Json;
import javax.json.stream.JsonParser;

class q43737601
{
  public static void main (String argv[]) throws Exception
  {
    String path = "config.json";
    int sum = 0;

    JsonParser p = Json.createParser (new FileReader (path));
    while (p.hasNext()) {
      JsonParser.Event e = p.next();
      switch (e) {
      case VALUE_NUMBER:
        sum += Integer.parseInt(p.getString());
        break;
      case KEY_NAME:
        if ("Type".equals(p.getString()))
          System.out.println(sum);
        break;
      }
    }
  }
}

If you run it, it displays 10. The example sums up all numbers up to a key called "Type".

I tried the above example with OpenJDK. It was necessary to follow the steps explained in this answer. I had to set the class path (-cp) in the compile command.

Upvotes: 1

Maxim Tulupov
Maxim Tulupov

Reputation: 1786

You can iterate over keys recursively, but you can't calculate sum, result will be unpredictable.

jsonObject.keySet not guarantee returns the keys in the same order as they appears in file.

Upvotes: 2

Related Questions