停用DeserializationConfig.Feature.USE_GETTERS_AS_SETTERS.
mapper.configure(DeserializationConfig.Feature.USE_GETTERS_AS_SETTERS, false);
使用静态导入使该行更短.
或者,如果您希望批注仅为此一个属性配置内容,而不指定上述全局设置,则将某些内容标记为“团队”的设置者.
public class Foo
{
@JsonSetter("teams")
public void asdf(List teams)
{
System.out.println("hurray!");
}
public List 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";
}