当我尝试解析下面的 JSON 数组时遇到一些小问题
{
"category": [
{
"id": "1",
"idRef": "1",
"name": "projet",
"products": [
{
"category": "1",
"content": "produit du projet , et sa description",
"id": "5",
"name": "ProdProj",
"price": "10000.0"
},
{
"category": "1",
"content": "application de pokemon potoo",
"id": "7",
"name": "pokedex",
"price": "10000.0"
},
{
"category": "1",
"content": "description du projet n2",
"id": "8",
"name": "projet2",
"price": "100.0"
},
{
"category": "1",
"content": "Construisez de vos reve",
"id": "9",
"name": "Pokedex Dream",
"price": "100.0"
}
]
},
{
"id": "2",
"idRef": "2",
"name": "jeux video",
"products": [
{
"category": "2",
"content": "Description du projet de de tout ce qui suit",
"id": "6",
"name": "Jeux video Project",
"price": "10000.0"
},
{
"category": "2",
"content": "The description pokedex is relouu",
"id": "10",
"name": "thePokedex",
"price": "100.0"
}
]
},
{
"id": "3",
"idRef": "3",
"name": "apps mobil",
"products": [
{
"category": "3",
"content": "description de l'application numéro2",
"id": "11",
"name": "application2",
"price": "100.0"
},
{
"category": "3",
"content": "azerazeraze mobil",
"id": "12",
"name": "azerMobil",
"price": "100.0"
}
]
}
]
}
使用此代码:
public class GsonFormatter {
private static Gson gson = new GsonBuilder()
.registerTypeAdapter(User.class, new UserDeserializer())
.registerTypeAdapter(Category.class, new CategoryDeserializer())
.registerTypeAdapter(Project.class, new ProjectDeserializer())
.create();
public static Gson getGson() {
return gson;
}
}
我有这个方法会出错:
"Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2"
Public ArrayList<Category>() {
return GsonFormatter.getGson().fromJson(json,
new TypeToken<List<Category>>() {}.getType());
所以我整夜都在努力。但我不知道出了什么问题。这是我第一次使用 JSON,所以我对这个愚蠢的问题感到抱歉...
最佳答案
该错误告诉您,在解析 JSON 并将其映射到您的 Category
类时,存在这样的情况:您的类需要一个对象,但 JSON 是一个数组。
查看您的 JSON,很容易看出它在哪里。您有一个 Category
对象数组。在其中一个中,products
是一个对象,在另一个中它是一个数组:
... \"products\":[{\"category\":\"1\",\"content\":\"Jeux ...
... \"products\":{\"category\":\"3\",\"content\":\"application ...
编辑回应评论:恕我直言,是的,服务器生成 JSON 的方式被破坏了。看起来是,如果一个类别中只有一个产品,它会将单个产品作为对象返回,但如果有多个产品,您会得到一个数组。理想情况下,即使只有一种产品,您也希望服务器始终返回一个数组。
如果您无法更改服务器,您需要做的是在解串器中处理它。您必须手动检查 products
字段并查看它是否是一个对象并将其转换为您的类的数组。
关于java - Json格式错误,已经获取数组时再请求数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20601882/