How do I sort the nested JSON objects using Gson Library?


am trying to parse my JSON data which looks like the data below. I've successfully some fields but am trying to get"name" under "0" under "category" under "terms".

    "ID": 1710,
    "status": "publish",
    "type": "post",
    "content": "Lorem ipsum",
    "parent": null,
    "format": "standard",
    "modified_tz": "UTC"
    "featured_image": {
    "ID": 1713,
    "title": "km",
    "status": "inherit",
    "type": "attachment",
    "terms": {
    "category": [    <<<<---AM REFERENCING HERE--->>>>>
    "ID": 2,
    "name": "Entertainment",
    "slug": "entertainment",
    "taxonomy": "category",
    "parent": null,
    "count": 30,


This is how i parsed the data:

List<Object> list = (List) new Gson.fromJson(response, List.class);
List<String, Object> mapPost = list.get(index);
List<String, Object> terms = (Map<String, Object>) mapPost.get("terms");
List<String, Object> category= (Map<String, Object>) terms.get("category");
List<String, Object> zero= (Map<String, Object>) category.get("0");
String tag = (String) zero.get("name");

Pleas help me what am i doing wrong?

The code you provided cannot even compile (broken Gson constructor invocation; Java does not provide List<K,V>...). Lists cannot be cast to maps in runtime too. The JSON is broken as well, but, assuming you've provided some code, I think you wanted to parse the name located at $[(index)].terms.category[0].name:

    final String name = gson.fromJson(response, JsonElement.class).getAsJsonArray()

You don't need to deserialize each nested object you're going to traverse (and this is more efficient from the performance point of view): just traverse the JSON tree.