Your JsonElement "test" is null for the object you are tring to find.
As you stated some objects have the video and others don't have.
Just change your code to:
if(test!=null && !test.isJsonNull()){
videos.add(test.getAsString());
}
質問
I have a JsonArray of elements and I want to check each object in the array for a field "video" some items in the array will not have the key, some will have the key and it will be null, I want to only find the elements that have the key and it is not null
public void addItems(ArrayList<JsonObject> j) {
if (j.size() > 0) {
ArrayList<String> videos = new ArrayList<String>();
for (int i = 0; i < j.size(); i++) {
try {
JsonElement test = j.get(i).getAsJsonObject().get("video");
if(!test.isJsonNull()){
videos.add(test.getAsString());
}
}
catch (JsonParseException e) {
e.printStackTrace();
}
}
if (videos.size() > 0) {
cloudCache.downloadVideos(videos);
}
}
}
I keep getting null pointer exception on the line
if(!test.isJsonNull()){
videos.add(test.getAsString());
}
解決
Your JsonElement "test" is null for the object you are tring to find.
As you stated some objects have the video and others don't have.
Just change your code to:
if(test!=null && !test.isJsonNull()){
videos.add(test.getAsString());
}