How to set jackson serialization depth level when using ObjectMapper?

Suppose I have the following classes:

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
}

Now, I want to load an object Employeeand serialize it with ObjectMapper:

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

when I run the code above, I see the json line as follows:

{
    "department" : {
        "address" : {
            "location" : {
                "streetName" : {}
            }
        }
    }
}

but I want to set the serialization depth to one level, I mean, when the code starts, I want to see the result as follows:

{
    "department" : {
    }
}

Note

I do not want to use jackson annotations, I want to configure the configuration when using the object mapper. for exmaple with mapper.setConfigor call mapper.disable.

+4
source share
2 answers

. : https://www.sghill.net/how-do-i-write-a-jackson-json-serializer-deserializer.html

JsonSerializer Override serialize().

 public class DepartmentSerializer extends JsonSerializer {
     @Override
     public void serialize(Department department, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
     //get parent json object name from jsonGenerator.getOutputContext().getParent().getCurrentName();
     // check name == null or name.equals("department") then serialize it unless return null

}

}

, @JsonSerialize

0

@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
}

@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
}

http://www.baeldung.com/jackson-ignore-properties-on-serialization

-1

Source: https://habr.com/ru/post/1691122/


All Articles