我正在尝试使用 Jackson 反序列化最初使用 Jackson 创建的一些 JSON。该模型有一个合成列表 getter:
public List<Team> getTeams() {
// create the teams list
}
Run Code Online (Sandbox Code Playgroud)
其中列表不是私有成员,而是即时生成的。现在这个序列化很好,但是在反序列化中使用了 getTeams,大概是因为 Jackson 看到了一个带有可变列表的 getter 并认为它可以将它用作 setter。getTeams 的内部结构依赖于 Jackson 尚未填充的其他字段。其结果是 NPE,即我认为订单是这里的问题之一,但不是我想要解决的问题。
所以,我想要做的是注释getTeams,这样它从来没有作为一个二传手,但被用作吸附剂。这可能吗?有什么建议?
禁用DeserializationConfig.Feature.USE_GETTERS_AS_SETTERS。
mapper.configure(DeserializationConfig.Feature.USE_GETTERS_AS_SETTERS, false);
Run Code Online (Sandbox Code Playgroud)
使用静态导入使这一行更短。
或者,如果您想要一个注解只为这个属性配置一些东西,而不是像上面那样指定全局设置,那么将一些东西标记为“团队”的设置器。
public class Foo
{
@JsonSetter("teams")
public void asdf(List<Team> teams)
{
System.out.println("hurray!");
}
public List<Team> getTeams()
{
// generate unmodifiable list, to fail if change attempted
return Arrays.asList(new Team());
}
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
String fooJson = mapper.writeValueAsString(new Foo());
System.out.println(fooJson);
// output: {"teams":[{"name":"A"}]}
// throws exception, without @JsonSetter("teams") annotation
Foo fooCopy = mapper.readValue(fooJson, Foo.class);
// output: hurray!
}
}
class Team
{
public String name = "A";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3384 次 |
| 最近记录: |