I'm trying to create objects with this JSON:
{
"data": {
"Prueba1": {
"id": 266,
"title": "Prueba1",
"name": "Prueba1",
"key": "Prueba1",
"lore": "Prueba1"
},
"Prueba2": {
"id": 111,
"title": "Prueba2",
"name": "Prueba2",
"key": "Prueba2",
"lore": "Prueba2"
}
},
"type": "prueba",
"version": "1.0"
}
The problem is that Gson is giving me the object 'data' but I can't not conver it to an array of objects.
My actual code is:
JsonParser parser = new JsonParser();
FileReader fr = new FileReader("route to archive json");
JsonElement datos = parser.parse(fr);
JsonElement heroes = datos.getAsJsonObject().get("data");
final Gson gson = new Gson();
final Type tipoListaEmpleados = new TypeToken<List<hero>>(){}.getType();
final List<hero> hero = gson.fromJson(heroes, tipoListaEmpleados);
System.out.println(hero.get(2));
But it's throwing error:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $
Any tip about the problem would be appreciated.
P.S: I understand that is giving all object, but I don't get the point of why is this happening, please help!!
EDIT: I'm working with an external API, that gives me that result, so I can't change the rest response, I need to convert to objects without adding []
EDIT2: Hero class looks like a single POJO :
public class hero
{
public int id;
public String title;
public String name;
public String key;
public String lore;
//constructor getters and setters
}
[and]if it's mention to be array of objects? It looks like a map to me.{}. But you are trying to deserialize aList<hero>which would expect the outer element to be an array with[]. This is why you're getting that error message.List<hero>. You haven't shown us whatHerolooks like but there's no array to convert into aListin your JSON.Prueba1andPrueba2let me thing those two should be in an array without thePruebaname for each element. Hving something like{"data":[{"id":266,...},{"id":111}]}