我有以下json:
"[{\"movieName\":\"A\",\"Leadactor\":\"\",\"leadActress\":\"\",\"movieTitle\":\"\",\"hero\":\"\",\"heroine\":\"\",\"source\":\"IMDB\"}," +
"{\"movieName\":\"\",\"Leadactor\":\"\",\"leadActress\":\"\",\"movieTitle\":\"B\",\"hero\":\"B1\",\"heroine\":\"B2\",\"source\":\"Netflix\"}," +
"{\"movieName\":\"C\",\"Leadactor\":\"C1\",\"leadActress\":\"C2\",\"movieTitle\":\"\",\"hero\":\"\",\"heroine\":\"\",\"source\":\"IMDB\"}," +
"{\"movieName\":\"D\",\"Leadactor\":\"D1\",\"leadActress\":\"D2\",\"movieTitle\":\"\",\"hero\":\"\",\"heroine\":\"\",\"source\":\"IMDB\"}," +
"{\"movieName\":\"\",\"Leadactor\":\"\",\"leadActress\":\"\",\"movieTitle\":\"E\",\"hero\":\"E1\",\"heroine\":\"E2\",\"source\":\"Netflix\"}]";
我正在使用杰克逊解析器将其映射到一个类:
我希望movieName 和movieTitle 映射到Java 类中的Name 属性。所以我写了下面的课程:
public static class MovieData {
@JsonProperty("Name")
private String name;
@JsonSetter({"movieName"})
private void setMovieName(final String name) {
if((name != null) && (! name.equals(""))) {
setNameInternal(name);
}
}
@JsonSetter("movieTitle")
private void setMovieTitle(final String name) {
if((name != null) && (! name.equals(""))) {
setNameInternal(name);
}
}
private void setNameInternal(final String name) {
this.name = name;
}
}
在我的真实 json 中,有很多字段,例如 movieName、movieTitle,我想将它们规范化为一个通用名称。
有没有像下面这样的简单语法可以减少代码重复:
public static class MovieData {
@JsonProperty("Name")
private String name;
@JsonSetter(value = { "movieName", "movieTitle" })
private void setName(final String name) {
if((name != null) && (! name.equals(""))) {
this.name=name;
}
}
}
上面的代码在 jsonSetter 上给了我错误:
Type mismatch: cannot convert from String[] to String.
编辑
如果Jackson 不支持,GSON 可以支持这个操作。
谢谢