我能够以这种方式获得privacyStatus,但是我似乎在他们的文档中看不到任何内容,其中显示了使用链式get语句的任何示例,例如您所拥有的。
((JSONObject)((JSONObject)((JSONArray) jsonObject.get("items")).get(0)).get("status")).get("privacyStatus")
编辑:我在我拥有的一些 android 代码中发现了这个小片段它将与http://json.org/java/库一起使用(如果与 android JSON 库不同,这非常相似)
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);
}
}