java gson在需要对象时遇到空数组问题
我试图使用gson处理一个json文件,但遇到了一个奇怪的错误。我从中读取的json(无法修改)有一种处理空字段的奇怪方式。它将[]放在没有数据的地方,使gson在需要对象时认为它是一个数组
gson的一个例子:
//non-empty field
"prizes":[
{
"year":"1902",
"category":"physics",
"share":"2",
"motivation":"\"in recognition of the extraordinary service they rendered by their researches into the influence of magnetism upon radiation phenomena\"",
"affiliations":[
{
"name":"Leiden University",
"city":"Leiden",
"country":"the Netherlands"
}
]
}
]
//empty field
"prizes":[
{
"year":"1903",
"category":"physics",
"share":"4",
"motivation":"\"in recognition of the extraordinary services they have rendered by their joint researches on the radiation phenomena discovered by Professor Henri Becquerel\"",
"affiliations":[
[]
]
}
]
这是我处理json的代码:
public static void main(String[] args) throws IOException {
// Get Gson object
Gson gson = new Gson();
// read JSON file data as String
String fileData = new
String(Files.readAllBytes(Paths.get("laureates.json")));
// parse json string to object
Example laur = gson.fromJson(fileData, Example.class);
// print object data
System.out.println("\n\nLaureates Object\n\n" + laur);
}
我已经安排好了所有的课程,我相信一旦这个问题得到解决,它就会起作用。 我得到的错误是“预期的BEGIN_对象,但在第1行第3401列是BEGIN_数组”(第3401列是第一个[]的确切位置)
# 1 楼答案
设置空对象的正确方法是不使用括号。你知道的。:-)
你可以做一个解决办法来移除支架
我希望这有帮助
# 2 楼答案
看起来gson需要一个对象,但返回了数组 尝试将示例更改为数组,如下所示
另见相关GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?
# 3 楼答案
您总是可以使用类型适配器来适应设计糟糕但格式良好的JSON文档。例如,以下类型适配器修复了您的案例:
现在假设您有以下映射:
然后:
输出: