Spring and Jackson: set json ignore dynamically

Question

I have some JPA models: "Category" and "Article":

@Entity
@Table(name = "categories")
public class Category {
private int id;
private String caption;
private Category parent;
private List<Category> childrenList;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@Column
public String getCaption() {
    return caption;
}

public void setCaption(String caption) {
    this.caption = caption;
}

@ManyToOne
@JoinColumn(name = "parent_id")
public Category getParent() {
    return parent;
}

public void setParent(Category parent) {
    this.parent = parent;
}

@OneToMany
@JoinColumn(name = "parent_id")
public List<Category> getChildrenList() {
    return childrenList;
}

public void setChildrenList(List<Category> childrenList) {
    this.childrenList = childrenList;
}
}



@Entity
@Table(name = "articles")
public class Article {
private int id;
private String caption;
private boolean isAvailable;
private String description;
private int price;
private Category category;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@Column
public String getCaption() {
    return caption;
}

public void setCaption(String caption) {
    this.caption = caption;
}

@Column(name = "is_available")
@Type(type = "org.hibernate.type.NumericBooleanType")
public boolean getIsAvailable() {
    return isAvailable;
}

public void setIsAvailable(boolean available) {
    isAvailable = available;
}

@Column
public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

@Column
public int getPrice() {
    return price;
}

public void setPrice(int price) {
    this.price = price;
}

@ManyToOne
@JoinColumn(name = "category_id")
public Category getCategory() {
    return category;
}

public void setCategory(Category category) {
    this.category = category;
}
}

Also i have some REST controller with two methods: 1)In the first method i need to get and serialize last 10 Articles, but i don't need "childrenList" and "parent" field in Categegory. 2)In the second method i need to get the same but serialize "parent" field.

How can i solve this? If i will use @JsonIgnore annotation to these fields then they will be never serialized. Or should i use DTO classes?

How can i dynamically set field for ignoring?


Show source
| java   | json   | jackson   | spring   | spring-mvc   2017-01-04 22:01 2 Answers

Answers to Spring and Jackson: set json ignore dynamically ( 2 )

  1. 2017-01-04 23:01

    Use a custom serializer, the psedo code is below.

    public class CategorySerializer extends StdSerializer<Category> {
    
        public CategorySerializer() {
            this(null);
        }
    
        public CategorySerializer(Class<Category> t) {
            super(t);
        }
    
        @Override
        public void serialize(Category value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
            // put the logic here to write the parent and child value or not
    
            // here is the example to how the data is serialized
            jgen.writeStartObject();
            jgen.writeNumberField("id", value.id);
            jgen.writeStringField("caption", value.caption);
    
            jgen.writeEndObject();
        }
    }
    

    Now, to utilize the custom serializer put this annotation above your Catagory entity class.

    @JsonSerialize(using = CategorySerializer.class)
    
  2. 2017-01-05 00:01

    I never use my Entitys for generating JSON, I think another set DTO classes will make you happier in the long run. My DTO typically has a constructor which takes the Entity as argument (it still needs a default constructor if you plan to use it for parsing incoming JSON).

    If you really want to use your Entities, I would recommend that you use MixIns, which allows you to register a MixIn class, that augments the serialization of a specific class.

    Here is a link to a MixIn example I made for another answer.

Leave a reply to - Spring and Jackson: set json ignore dynamically

◀ Go back