将JSON映射到POJO时出现java UnrecognizedPropertyException
我使用Jackson API在一组POJO类的帮助下将JSON文件解析为对象。但是当ObjectMapper到达@title字段时,会出现以下无法识别的PropertyException错误:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "@title" (class gmit.Exit), not marked as ignorable (2 known properties: "title", "direction"])
at [Source: C:\Users\Brian\Documents\Eclipse\Projects\AI_Project_Grail_Quest_3\bin\resources\game.json; line: 13, column: 24] (through reference chain: gmit.Location["location"]->Object[][0]->gmit.Location["exit"]->Object[][0]->gmit.Exit["@title"])
这是正在解析的JSON文件:
http://hastebin.com/qamacarumu.pl
我知道这是因为属性未被识别为错误状态,但我不确定为什么,因为我在Exit POJO中声明了这个字段。有人试图像这样在字段中添加@JsonProperty,但似乎不起作用:
@JsonProperty("title")
private String[] title;
有人知道如何解决这个错误吗?或者,您可以解释一下,为什么在退出POJO中存在标题字段的情况下仍会抛出此错误
以下是POJO的:
地点:
import java.util.Arrays;
public class Location {
private Location[] location;
private String description;
private String name;
private Exit[] exit;
public Location[] getLocation() {
return location;
}
public void setLocation(Location[] location) {
this.location = location;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public Exit[] getExit() {
return exit;
}
public void setExit(Exit[] exit) {
this.exit = exit;
}
@Override
public String toString() {
return "Location [location=" + Arrays.toString(location)
+ ", description=" + description + ", name=" + name + ", exit="
+ Arrays.toString(exit) + "]";
}
}
出口:
public class Exit {
@JsonProperty("title")
private String[] title;
private String[] direction;
public String[] getTitle() {
return title;
}
public void setTitle(String[] title) {
this.title = title;
}
public String[] getDirection() {
return direction;
}
public void setDirection(String[] direction) {
this.direction = direction;
}
}
# 1 楼答案
注释不应该是
@JsonProperty("@title")
,因为这是JSON中键的名称吗? 还要注意的是,Jackson根据您的版本提供了两个不同的名称空间。这很容易成为一个陷阱org.codehaus.jackson
com.fasterxml.jackson
所以一定要使用正确的注释