简体   繁体   中英

How to ignore empty lists in jackson?

I have the following entities that i want my web service to pass as jsons

@Entity(name = "tests")
public class Test {

    @Id
    @GeneratedValue
    private int id;

    @Column(name = "test_name")
    private String name;

    @JoinColumn(name = "test_id")
    @OneToMany(cascade = CascadeType.REMOVE)
    private List<Question> questions;

}

@Entity(name = "questions")
public class Question {

    @Id
    @GeneratedValue
    private int id;

    @Column
    private String question;

    @Column(name = "is_multi_select")
    private boolean isMultiSelect;

    @JoinColumn(name = "question_id")
    @OneToMany(cascade = CascadeType.REMOVE)
    private List<Answer> answers;

}

The problem is i want the question list not to be included in my json, but i just can't make jackson ignore them.

I tried to annotated the question list with @JsonIgnore , but no result. How do i do this?

PS

Forgot to mention that the serialization is done via jersey, and here's the method that actually returns my test list

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/tests")
public Response getLanguageList() {
    List<Test> tests = TestDao.getTests();
    return Response.status(200).entity(tests).build();
}

You have to configure your mapper to ignore empty arrays:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);

To ignore a specific property, the com.fasterxml.jackson.annotation.JsonIgnore annotation should do:

@JsonIgnore
@JoinColumn(name = "test_id")
@OneToMany(cascade = CascadeType.REMOVE)
private List<Question> questions;

EDIT: You may need to enable Jackson with this in your web.xml :

<init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
</init-param>

or configuring though code:

ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);

Reference: https://jersey.java.net/documentation/1.19.1/json.html

@JsonInclude(JsonInclude.Include.NON_EMPTY)

NON_EMPTY使仅包含非null字段,而不包含空集合类型字段。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM