1

I am trying to parse a Json file with a for loop cycle. The problem is when I try to get a key that doesn't exist on the array element. Here an example of the Json file:

{
"data": [
    {
        "id": "1445168029094512_1863149637296347",
        "created_time": "2017-02-12T11:00:18+0000",
        "likes": {
            "data": [],
            "summary": {
                "total_count": 0
            }
        }
    },
    {
        "shares": {
            "count": 1
        },
        "id": "1445168029094512_1862494140695230",
        "created_time": "2017-02-11T00:30:17+0000",
        "likes": {
            "data": [],
            "summary": {
                "total_count": 0
            }
        }
    }]
 }

Code sample:

Gson gson = new Gson();
String responseData = response.toString();    
JsonObject jsonFile = gson.fromJson(responseData, JsonObject.class);
for(int i = 0 ; i < array.size(); i++){
    Data data = new Data();
    if(array.get(i).getAsJsonObject().get("shares").getAsJsonObject().get("count")!= null) {
        jsonElement = array.get(i).getAsJsonObject().get("shares").getAsJsonObject().get("count");
        element = jsonElement.toString();
        data.setShares(Long.parseLong(element));
    }
}

The problem is that on the first element of the array the key "shares" doesn't exists, so this cause a NullPointerException. I dont know how to handle this, because this is on a for loop and sometimes it would have this key and sometimes no.

Thanks in advance!

Gaëtan Maisse
  • 12,208
  • 9
  • 44
  • 47
MathiasMS
  • 35
  • 1
  • 4
  • You should first check if `shares` is null. Something along the lines of `if(array.get(i).getAsJsonObject().get("shares") != null && array.get(i).getAsJsonObject().get("shares").getAsJsonObject().get("count")!= null)`. – Iakovos Feb 12 '17 at 12:37
  • OMG I don't see that, my bad. THANKS MAN !!! – MathiasMS Feb 12 '17 at 12:48

0 Answers0