0

I have a JSON similar to this which I get it by sending HTTP request.

{
      "0": {
        "name": "Chunk",
        "type": "magic",
        "item": "Chestplate",
        "item_min_lvl": "70",
        "id": {
          "health": "0.3",
          "spell": "24%",
          "life": "0.1",
          "xp": "24%",
          "loot": "22%"
        },
        "def": "67"
      },
      "1": {
        "name": "Thor",
        "type": "normal",
        "item": "Shoe",
        "item_min_lvl": "12",
        "id": {
          "xp": "24%"
        },
        "def": "12"
      },
      "2": {
        "name": "Clipper",
        "type": "normal",
        "item": "Sword",
        "item_min_lvl": "51",
        "id": {
          "health": "1",
          "life": "0.12",
          "xp": "4%"
        },
        "min_dam": "11",
        "max_dam": "7"
      }

}

Here is my code:

java.lang.reflect.Type type = new TypeToken<ArrayList<Map<String, Object>>>(){}.getType();
ArrayList<Map<String, Object>> list = gson.fromJson(json, type);//Error here
for(Map<String, Object> m : list)
{
    //blah
}

It returns this error Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Can anyone help me to solve this error? I am new to JSON and GSON. Please note, some of the the "items" aren't the same so I have to use TypeToken.

1 Answer 1

1

You json does not include arrays (with syntax []) but objects (with syntax {}).

You probably need to use new TypeToken<Map<String, <Map<String, Object>>>>(){}.getType();

Sign up to request clarification or add additional context in comments.

5 Comments

do I need to modify for(Map<String, Object> m : list) ?
yes, but rather using for(Map<String, Object> m : list.values()) as list will be a Map<String, Map<String, Object>>
Uhh same error at this ` ArrayList<Map<String, Map<String, Object>>> list = gson.fromJson(json, type);`
There is no array. java.lang.reflect.Type type = new TypeToken<Map<String, <Map<String, Object>>>>(){}.getType();Map<String, <Map<String, Object>>> map = gson.fromJson(json, type); for(Map<String, Object> m : map.values()) { /****/ } Also, Im not sure you need to specify the while type hierarchy using gson. Use JSonObject obj = gson.fromJson();
If your json might differ, consider using JsonObject and adding checks to see if the property you want to read is actually a jsonobject. In other word, go down the object hierarchy manually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.