在Java中从Object转换为JSON时的额外意外部分

时间:2015-02-05 18:51:38

标签: java json serialization jackson

我有一个Object,当我使用对象映射器将对象转换为String并返回它时。除了这个对象的属性,我发现了一个额外的键。例如

public class Person(){

private int age;
private String firstName;
private String lastName;

setter and getter for those properties above,


public String getFullName(){

return this.firstName + this.lastName;
}



}

为什么,我为这个人类获得的JONS包含一个名为FullName的密钥?为什么我能骑这个?是因为Java找到了fullName的getter并自动认为FullName是一个属性,所以当我从Person对象转换为JSON时,它会添加它吗?

2 个答案:

答案 0 :(得分:1)

Jackson通常会在提供的POJO上序列化所有getter方法(除非另有配置)。要忽略fullName属性的序列化,只需在getter-method上添加@JsonIgnore

@JsonIgnore
public String getFullName() {
    return this.firstName + this.lastName;
}

来自JavaDocs

  

标记注释,指示基于内省的序列化和反序列化功能将忽略带注释的方法或字段。也就是说,不应该考虑" getter"," setter"或"创作者"。

因此,基本上这意味着标记为@JsonIgnore的所有方法或字段将被忽略以进行序列化和反序列化。

答案 1 :(得分:-1)

我认为ObjectMapper也会查看getter来序列化它,所以如果你只想序列化字段,那么就可以像打击一样创建mapper对象

    ObjectMapper mapper = new ObjectMapper();                                                
    mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

或者,还有另一种方法,您可以在要序列化的类中指定它。在类

之前添加以下注释
  @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) 
相关问题