kaderud
kaderud

Reputation: 5497

Using Gson to parse JSON with Objects but needing to exclude Arrays

I have a need to parse a JSON string containing Objects, but there can also be Arrays in the JSON, which I don't need, and it's currently crashing with:

com.google.gson.JsonSyntaxException: 
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

If I remove all the Arrays from the JSON, it works perfectly fine to parse the JSON with my POJO using the following code:

Type type = new TypeToken<Map<String, UsersPOJO>>(){}.getType();
Map<String, UsersPOJO> myUsers = gson.fromJson(JSONString, type);

But I'm having no luck parsing whenever there's Arrays in the JSON. I don't need, nor do I want to parse the Arrays, but if it's necessary, parsing the Arrays and then discarding the result would be okay.

How do I accomplish this with Gson? Or any other Java JSON library for that matter. Gson isn't a requirment.

This is an example of the JSON I'd be parsing:

{
   "1002001":{  
      "level":2,
      "name":"CaptKrunch",
      "uid":1002001,
      "user":{  
         "age":21,
         "city":"None",
         "country":"United States",
         "creation":1269969663
      },
      "meta":{  
         "score":1762,
         "rank":78
      }
   },
   "1003001":{  
      "level":11,
      "name":"LtRaine",
      "uid":1003001,
      "user":{  
         "age":35,
         "city":"LA",
         "country":"United States",
         "creation":1269369663
      },
      "meta":{  
         "score":11562,
         "rank":11
      }
   },
   "tags_1002001": [
     "conqurer",
     "almighty"
   ]
}

Upvotes: 3

Views: 539

Answers (1)

Rustam
Rustam

Reputation: 1407

You can skip array, if parse JSON string to JsonElement and iterate all elements:

Gson gson = new Gson();

//Type type = new TypeToken<Map<String, UsersPOJO>>(){}.getType();
//Map<String, UsersPOJO> myUsers = gson.fromJson(jsonString, type);

JsonParser parser = new JsonParser();
JsonElement topElement = parser.parse(jsonString);
Map<String, UsersPOJO> myUsers = new HashMap<>();
for (Map.Entry<String, JsonElement> entry : topElement.getAsJsonObject().entrySet()) {
    if (entry.getValue().isJsonArray()) {
        //skip or process array
    } else {
        myUsers.put(entry.getKey(), gson.fromJson(entry.getValue(), UsersPOJO.class));
    }
}

Upvotes: 1

Related Questions