755
755

Reputation: 3091

Jackson JSON: Serialize certain properties under different view?

if I have a class called "TreeNode" with an instance variable (among others) called "children", which is an array of other TreeNodes, is there a way such that I can serialize the TreeNode instance under one JsonView, but serialize all the TreeNodes in my "children" array under a different JsonView?

What I'm trying to accomplish is: when I serialize a single TreeNode, I want all the properties in that TreeNode to be serialized, including the list of its children, but I don't want all the properties of the children to be serialized (such as the child's "children" array). Basically if I serialize a TreeNode I only want to see that TreeNode and the children one level down. There are also other properties in the children that I would like to hide, only when they are serialized as part of a "children" array.

Is there a way I can accomplish this with JsonViews or some other Jackson feature? Thanks

Upvotes: 0

Views: 930

Answers (1)

Vivin Paliath
Vivin Paliath

Reputation: 95588

For custom serialization logic, you will have to implement your own JsonSerializer.

For example:

public class TreeNodeSerializer extends JsonSerializer<TreeNode> {

    @Override
    public void serialize(TreeNode value, JsonGenerator generator,
                          SerializerProvider provider) throws IOException,             JsonProcessingException {

        generator.writeStartObject();
        generator.writeStringField("value", value.getValue());
        generator.writeNumberField("numValue", value.getNumValue());

        generator.writeArrayFieldStart("children");
        for(TreeNode child : value.getChildren()) {
            generator.writeStringField("value", child.getValue());
            generator.writeNumberField("numValue", child.getNumValue());
        }
        generator.writeEndArray();

        generator.writeEndObject();
    }
}

Upvotes: 3

Related Questions