我需要映射以下JSON:
(ListBox.Items[2] as DataItem).SelectedIndex = 1;
看起来像这样: JSON
在我不需要"覆盖"字段(我的域类只有ID和名称)。现在,当我需要它时,我也遇到了问题。
这是我用来将我的JSON映射为字符串的代码行(就像我说的,如果我只坚持id和name字段,它可以正常工作)。
[{"id":7346,"name":"The Legend of Zelda: Breath of the Wild","cover":{"url":"//images.igdb.com/igdb/image/upload/t_thumb/jk9el4ksl4c7qwaex2y5.jpg","cloudinary_id":"jk9el4ksl4c7qwaex2y5","width":2709,"height":3816}},{"id":2909,"name":"The Legend of Zelda: A Link Between Worlds","cover":{"url":"//images.igdb.com/igdb/image/upload/t_thumb/r9ezsk5yhljc83dfjeqc.jpg","cloudinary_id":"r9ezsk5yhljc83dfjeqc","width":406,"height":362}}]
我的 Suggestion.java 类:
List<Suggestion> suggestions = mapper.readValue(requestString, new TypeReference<List<Suggestion>>(){});
我的 Cover.java 类:
public class Suggestion {
private long id;
private String name;
private Cover cover;
public Suggestion(){
}
public Suggestion(long id, String name, Cover cover) {
this.id = id;
this.name = name;
this.cover = cover;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public Cover getCover() {
return cover;
}
}
我已经使用http://www.jsonschema2pojo.org/来获得这个想法(其他属性不是必需的)并且我不确定它为什么不再起作用。
那么这可能是什么问题?
答案 0 :(得分:2)
让我们来看看导致问题的原因。如果您使用已提供的类运行代码,您将获得以下异常:
线程中的异常&#34; main&#34; com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:无法识别的字段&#34; cloudinary_id&#34;
您的示例中的JSON如下:
[
{
"id": 7346,
"name": "The Legend of Zelda: Breath of the Wild",
"cover": {
"url": "//images.igdb.com/igdb/image/upload/t_thumb/jk9el4ksl4c7qwaex2y5.jpg",
"cloudinary_id": "jk9el4ksl4c7qwaex2y5",
"width": 2709,
"height": 3816
}
},
{
"id": 2909,
"name": "The Legend of Zelda: A Link Between Worlds",
"cover": {
"url": "//images.igdb.com/igdb/image/upload/t_thumb/r9ezsk5yhljc83dfjeqc.jpg",
"cloudinary_id": "r9ezsk5yhljc83dfjeqc",
"width": 406,
"height": 362
}
}
]
您错过了使用@JsonProperty
注释将JSON指定给属性字段映射。将您的Cover
课程更新为:
public class Cover {
private String url;
@JsonProperty("cloudinary_id")
private String cloudinaryId;
private Integer width;
private Integer height;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCloudinaryId() {
return cloudinaryId;
}
public void setCloudinaryId(String cloudinaryId) {
this.cloudinaryId = cloudinaryId;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
当JSON字段将1:1映射到类字段名称时,您不必使用此批注。当JSON使用与Java类不同的命名时,它是必需的。