1

I'm having an issue trying to parse a string using json-simple, this is the sample string:

{
 "items": [
  {
   "id": "uy0nALQEAM4",
   "kind": "youtube#video",
   "etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/x3SYRGDdvDsN5QOd7AYVzGOJQlM\"",
   "status": {
    "uploadStatus": "processed",
    "privacyStatus": "public",
    "license": "youtube",
    "embeddable": true,
    "publicStatsViewable": true
   }
  }
 ]
}

This is my code:

JSONParser parser = new JSONParser();
Object obj = parser.parse(result);
JSONObject jsonObject = (JSONObject) obj;

System.out.println("privacyStatus: "
                    + (String) jsonObject.get("items[0].status.privacyStatus")
                    + "\nembeddable: "
                    + (String) jsonObject.get("items[0].status.embeddable")
                    + "\npublicStatsViewable: "
                    + (String) jsonObject.get("items[0].status.publicStatsViewable"));

The output is:

privacyStatus: null
embeddable: null
publicStatsViewable: null

What stupid mistake am I making?

m4design
  • 2,112
  • 3
  • 21
  • 28

2 Answers2

2

I was able to get the privacyStatus this way, however I cant seem to see anything in their documentation where they show any examples of using a chained get statement like the ones you have.

((JSONObject)((JSONObject)((JSONArray) jsonObject.get("items")).get(0)).get("status")).get("privacyStatus")

Edit: I found this little snippet in some android code I have It will work with the http://json.org/java/ library (this is very similar if not the same as the android JSON library)

   public static void main(String[] args) 
{
    // this is the same JSON string in the OP
    String jsonString = "{ \"items\": [  {   \"id\": \"uy0nALQEAM4\",   \"kind\": \"youtube#video\",   \"etag\": \"\\\"g-RLCMLrfPIk8n3AxYYPPliWWoo/x3SYRGDdvDsN5QOd7AYVzGOJQlM\\\"\",   \"status\": {    \"uploadStatus\":\"processed\",    \"privacyStatus\": \"public\",    \"license\": \"youtube\",    \"embeddable\": true,    \"publicStatsViewable\": true   }  } ]}";
    JSONObject object = new JSONObject(jsonString);
    try {
        String myValue = (String)getJSONValue("items[0].status.privacyStatus", object);
        System.out.println(myValue);
    } catch (JSONException ex) {
        Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public static Object getJSONValue(String exp, JSONObject obj) throws JSONException {
    try {
        String [] expressions = exp.split("[\\.|\\[|\\]]");
        Object currentObject = obj;
        for(int i=0; i < expressions.length; i++) {
            if(!expressions[i].trim().equals("")) {
                System.out.println(expressions[i] + " " + currentObject);

                if(currentObject instanceof JSONObject) {
                    Method method = currentObject.getClass().getDeclaredMethod("get", String.class);
                    currentObject = method.invoke(currentObject, expressions[i]);
                } else if(currentObject instanceof JSONArray) {
                    Method method = currentObject.getClass().getDeclaredMethod("get", Integer.TYPE);
                    currentObject = method.invoke(currentObject, Integer.valueOf(expressions[i]));
                } else {
                    throw new JSONException("Couldnt access property " + expressions[i] + " from " + currentObject.getClass().getName());
                }
            }
        }
        return currentObject;
    } catch (NoSuchMethodException ex) {
         throw new JSONException(ex);
    } catch (IllegalAccessException ex) {
         throw new JSONException(ex);
    } catch (IllegalArgumentException ex) {
         throw new JSONException(ex);
    } catch (InvocationTargetException ex) {
         throw new JSONException(ex);
    }
}
ug_
  • 11,267
  • 2
  • 35
  • 52
  • This does work, but it sure is ugly as hell lol. Maybe I should use another library? – m4design Jun 02 '13 at 02:32
  • 1
    I personally prefer GSON its googles support for JSON check out this thread http://stackoverflow.com/questions/338586/a-better-java-json-library . All JSON librarys seem to be kind of bulky and have no great way of accessing nested objects in a clean way. To do this I would recommend using something like SpEL (spring expression language) or create a small class with some basic java reflection. If you like I can send something over I have a few snipplets here and there. edit: forgot to add http://json.org/java/ – ug_ Jun 02 '13 at 03:09
2

I guess it's a library limitation to solve it in a clean way. I found minimal library: https://github.com/ralfstx/minimal-json

Which is very nice and clean. Then did the following to do what I wanted:

JsonObject jsonObject = JsonObject.readFrom(result.toString())
          .get("items").asArray().get(0).asObject().get("status").asObject();

Then I can do:

boolean isPublic = jsonObject.get("privacyStatus").asString().equals("public");
boolean isEmbbedable = jsonObject.get("embeddable").asBoolean();
m4design
  • 2,112
  • 3
  • 21
  • 28