使用ObjectMapper时如何设置jackson序列化深度级别?

Ras*_*ari 6 java serialization json jackson objectmapper

Assuem我有以下类:

public class Employee {
    private Department department;

    // other fields, getters and setters omited for brevtity
}

public class Department {
    private Address address;

    // other fields, getters and setters omited for brevtity
}

public class Address {
    private Location location;

    // other fields, getters and setters omited for brevtity
}

public class Location {
    private String streetName;

    // other fields, getters and setters omited for brevtity
}
Run Code Online (Sandbox Code Playgroud)

现在,我想加载Employee对象并序列化它ObjectMapper:

public void serializeEmployee() {
    Employee employee = entityManager.load(Employee.class, 1);
    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(student));
}
Run Code Online (Sandbox Code Playgroud)

当我在代码上面运行时,我看到像这样的json字符串:

{
    "department" : {
        "address" : {
            "location" : {
                "streetName" : {}
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我想将序列化深度设置为一个级别,我的意思是当代码运行时,我希望看到这样的结果:

{
    "department" : {
    }
}
Run Code Online (Sandbox Code Playgroud)

注意

我不想使用jackson注释,我想在使用mapper对象时设置配置.对于电话mapper.setConfigmapper.disable.

小智 -3

您可以通过对字段使用注释 @JsonIgnore 或 @JsonIgnoreProperties(value = { "fieldName" }) 来忽略属性

public class MyDto {

    private String stringValue;
    @JsonIgnore
    private int intValue;
    private boolean booleanValue;

    public MyDto() {
        super();
    }

    // standard setters and getters are not shown
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用 @JsonIgnoreProperties(value = { "fieldName" })

@JsonIgnoreProperties(value = { "intValue" })
public class MyDto {

    private String stringValue;
    private int intValue;
    private boolean booleanValue;

    public MyDto() {
        super();
    }

    // standard setters and getters are not shown
}
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请查看http://www.baeldung.com/jackson-ignore-properties-on-serialization