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?

5
  • maybe items[0] is null Commented Jun 2, 2013 at 1:27
  • Well is it? the sample text doesn't seems null to me. I'm a json/js noob btw. Commented Jun 2, 2013 at 1:29
  • what I mean is that maybe the string you are trying to parse is actually null, but that obviously isn't the case if you are parsing what you posted as an example Commented Jun 2, 2013 at 1:33
  • No it isn't, the is taken from the console when I debugged the code. Commented Jun 2, 2013 at 1:39
  • You should consider using another library... For JSON value manipulations, there is nothing that matches Jackson. Use that. Commented Jun 2, 2013 at 2:48

2 Answers 2

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This does work, but it sure is ugly as hell lol. Maybe I should use another library?
I personally prefer GSON its googles support for JSON check out this thread 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 json.org/java
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.