[英]Json to objects in Java (Gson)
I'm trying to create objects with this JSON: 我正在尝试使用此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. 问题在于,Gson给了我对象“数据”,但我不能将其转换为对象数组。
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. 关于这个问题的任何提示将不胜感激。
PS: I understand that is giving all object, but I don't get the point of why is this happening, please help!! PS:我知道这是万能的,但我不明白为什么会这样,请帮忙!
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 [] 编辑:我正在使用一个外部API,它给我那个结果,所以我不能更改其余响应,我需要转换为对象而不添加[]
EDIT2: Hero class looks like a single POJO : EDIT2:Hero类看起来像一个POJO:
public class hero
{
public int id;
public String title;
public String name;
public String key;
public String lore;
//constructor getters and setters
}
Your JSON doesn't actually have a JSON Array in it. 您的JSON实际上没有JSON数组。 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 您可以使用http://www.jsoneditoronline.org/来验证JSON并相应地进行调整
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.