Jota Ge Jota Ge - 1 month ago 5
JSON Question

Json to objects in Java (Gson)

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
}

Answer

Your JSON doesn't actually have a JSON Array in it. Try this...although this might not be the exact structure you're looking for.

{
    "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"
}

You can use http://www.jsoneditoronline.org/ to verify your JSON and tweak accordingly

Comments