tags:

views:

190

answers:

3

Guys, simple situation -

  1. read a json file
  2. discover all key-value pairs
  3. compare key-value pairs

I tried gson, package from json.org, but can't seem to get far with it.

Can someone please provide a clear sample in Java on how to take a file, read it, end up with json objec i can get key/value pairs from

thanks so much

+3  A: 

With Gson (assuming that you have on object {...} on the top level of your json file):

final JsonParser parser = new JsonParser();
final JsonElement jsonElement = parser.parse(new FileReader("/path/to/myfile"));
final JsonObject jsonObject = jsonElement.getAsJsonObject();

for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {
   final String key = entry.getKey();
   final JsonElement value = entry.getValue();
   ....
}

In response to your comment:

You should certainly avoid re-parsing the json from a string. Use something like:

... else if (value.isJsonArray()) {
   final JsonArray jsonArray = value.getAsJsonArray();
   if (jsonArray.size() == 1) {
      runThroughJson(jsonArray.get(0));
   } else {
        // perform some error handling, since
        // you expect it to have just one child!
   }

} 
Chris Lercher
Chris - you are awesome. Thank you so very much for your help!
mac
You're welcome!
Chris Lercher
I will be using recursion to drill down to inner elements. Does gson provide a method to drop []?
mac
I'm not sure if I understand what "drop []" means in this context, but you can always use `value.isJsonArray()` to check, if the current element is an array, and then decide to discard it.
Chris Lercher
JsonObject begins and ends in {}. As i drill down i see [{}]. In this case i would like to trim [] on both sidesif (value.isJsonObject()) { loop(value.getAsJsonObject());} else { int ix = value.getAsString().indexOf('['); int ig = value.getAsString().lastIndexOf(']'); String a = value.getAsString().substring(ix, ig); JsonElement jsonElement = parser.parse(a); loop(jsonElement.getAsJsonObject());}
mac
+1  A: 

Consider this:

private void runThroughJson(JsonObject jsonObject) {
    for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {

        final String key = entry.getKey();
        final JsonElement value = entry.getValue();

        System.out.println(key + " - " + value);

        if (value.isJsonObject()) {
            runThroughJson(value.getAsJsonObject());
        } else {                
            int ix = value.getAsString().indexOf('[');
            int ig = value.getAsString().lastIndexOf(']');

            System.out.println(ix);
            System.out.println(ig);

            String a = value.getAsString().substring(ix, ig);
            JsonElement jsonElement = parser.parse(a);
            runThroughJson(jsonElement.getAsJsonObject());
        }
    }
}

Logically, it seems alright, however, i get an exception:

Exception in thread "main" java.lang.IllegalStateException
    at com.google.gson.JsonArray.getAsString(JsonArray.java:133)
    at com.cme.esg.bk.TryGson.runThroughJson(TryGson.java:46)
    at com.cme.esg.bk.TryGson.runThroughJson(TryGson.java:44)
    at com.cme.esg.bk.TryGson.goForIt(TryGson.java:32)
    at com.cme.esg.bk.TryGson.main(TryGson.java:16)

Can you please advise that am i missing.

mac
Mind matching line numbers in the code? It's hard to see any problems without correct line numbers
TheLQ
A: 

XStream is good for JSON:

http://xstream.codehaus.org/json-tutorial.html

Brian