Serialize with Jackson up to a Certain Depth in Nested Arrays

Viewed 443

I have followed this in order to keep Jackson from returning infinite depth when serializing to JSON certain nested objects: Serialize recursive objects with jackson up to a certain depth

This entails creating a new BeanSerializer and overriding the serializeFields method. This works fine unless you are serializing Objects contained in Arrays. When my serializeFields method is called, I have no clue if I'm in an array or not, so for every call, my depth counter is actually counting every object in the nested array. So basically I am just doing a depth first search, and when reaching my limit, I just stop processing all elements in the array, instead of continuing with the next element.

I think I need to overwrite the ObjectArraySerializer.serializeContents method, so I can pass information about the array to my serializeFields method, but I am not sure how to go about this.

Does anyone have any guidance?

--Edit--

I have a reproducible error.

Input:

    stdin:3

Code:

    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.BeanDescription;
    import com.fasterxml.jackson.databind.JsonSerializer;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.ObjectWriter;
    import com.fasterxml.jackson.databind.SerializationConfig;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import com.fasterxml.jackson.databind.SerializerProvider;
    import com.fasterxml.jackson.databind.json.JsonMapper;
    import com.fasterxml.jackson.databind.module.SimpleModule;
    import com.fasterxml.jackson.databind.ser.BeanSerializer;
    import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
    import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase;
    
    import java.io.IOException;
    import java.util.concurrent.atomic.AtomicInteger;
    
    public class TestJackson {
    
        public static void main(String[] args) throws IOException {
            Node aNode = new Node("A");
            Node bNode = new Node("B");
            Node[] NodeArr = new Node[] {aNode,bNode};
            aNode.setChild(NodeArr);
            bNode.setChild(NodeArr);
    
            //System.out.print(defMapper.writeValueAsString(aNode)); //Bombs, as expected
    
            for (int i = 0; i < Integer.parseInt(args[0]); i++) {
                System.out.println("Depth: " + i);
                System.out.println(serialiseWithDepth(aNode, i));
            }
        }
    
        private static ObjectMapper defMapper = JsonMapper.builder()
                .enable(SerializationFeature.INDENT_OUTPUT)
                .build();
    
        private static ObjectMapper mapper = JsonMapper.builder()
                .enable(SerializationFeature.INDENT_OUTPUT)
                .addModule(createNodeModule())
                .build();
    
        private static String serialiseWithDepth(Node node, int maxDepth) throws JsonProcessingException {
            ObjectWriter writer = mapper.writerFor(Node.class)
                    .withAttribute(NodeDepthBeanSerializer.DEPTH_KEY, new AtomicInteger(maxDepth));
    
            return writer.writeValueAsString(node);
        }
    
        private static SimpleModule createNodeModule() {
            SimpleModule nodeModule = new SimpleModule("NodeModule");
            nodeModule.setSerializerModifier(new BeanSerializerModifier() {
                @Override
                public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
                    if (beanDesc.getBeanClass() == Node.class) {
                        return new NodeDepthBeanSerializer((BeanSerializerBase) serializer);
                    }
                    return super.modifySerializer(config, beanDesc, serializer);
                }
            });
            return nodeModule;
        }
    }
    
    class NodeDepthBeanSerializer extends BeanSerializer {
    
        public static final String DEPTH_KEY = "maxDepthSize";
    
        public NodeDepthBeanSerializer(BeanSerializerBase src) {
            super(src);
        }
    
        @Override
        protected void serializeFields(Object bean, JsonGenerator gen, SerializerProvider provider) throws IOException {
            AtomicInteger depth = (AtomicInteger) provider.getAttribute(DEPTH_KEY);
            if (depth.decrementAndGet() >= 0) {
                super.serializeFields(bean, gen, provider);
            }
        }
    }
    
    class Node {
    
        public Node() {
            this("",null, (new NodeHolder(new Node[]{})));
        }
        public Node(String id){
            this(id,null, (new NodeHolder(new Node[]{})));
        }
        public Node(String theId,Node[] theChild,NodeHolder holder){
            setId(theId);
            setChild(theChild);
            setHolder(holder);
        }
    
        private String id;
    
        private Node[] child;
    
        private NodeHolder holder;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public Node[] getChildren() {
            return child;
        }
    
        public void setChild(Node[] child) {
            this.child = child;
        }
    
        public NodeHolder getHolder() {
            return holder;
        }
    
        public void setHolder(NodeHolder holder) {
            this.holder = holder;
        }
    }
    class NodeHolder {
        public NodeHolder(Node[] theNodes) {
            this.nodes = theNodes;
        }
    
        public Node[] getNodes() {
            return nodes;
        }
    
        public void setNodes(Node[] nodes) {
            this.nodes = nodes;
        }
    
        private Node[] nodes;
    }

Output:

Depth: 0
{ }
Depth: 1
{
  "id" : "A",
  "holder" : {
    "nodes" : [ ]
  },
  "children" : [ { }, { } ]
}
Depth: 2
{
  "id" : "A",
  "holder" : {
    "nodes" : [ ]
  },
  "children" : [ {
    "id" : "A",
    "holder" : {
      "nodes" : [ ]
    },
    "children" : [ { }, { } ]
  }, { } ]
}

Notice how the children arrays are all empty, but they have exactly right number of fields? It does a depth-first search, them returns without moving to the next array element when the counter is < 0. Not sure the best way to go about solving it.

I also am aware that the example doesn't make sense, and is probably poor design - it's a reproduction of part of a massive web app bean structure that I don't have the time or skills to redesign at the moment :D

--Edit--

See a working example here: https://repl.it/@csxdog/Serialize-with-Jackson-up-to-Certain-Depth-in-Nested-Arrays

1 Answers

Since noone has responded with an answer: For this issue, since I was exposing a REST API, I ended up creating some non-recursive wrapper objects to hold the resulting value, so that Jackson could parse it easily. This is probably the best practice in the field. This was a Hackathon project, so I was looking for the quickest fix originally.

Related