'Easy way of converting ArrayNode to ObjectNode

I have a custom deserializer CustomDeserializer extending StdDeserializer from Jackson.

I override the deserialize method to give me ObjectA. I want to store the JSON received as a BSON field in ObjectA.

I have two parts here that I want to optimize (or more if you spot more!):

  1. How can I easily convert the json ArrayNode to an ObjectNode without instantiating a new ArrayNode and manually adding individual nodes to it? Is there already an existing API for that?
  2. Is there a way to more quickly convert ObjectNode to BSON or ArrayNode to BSON or the received JSON to BSON?

Basically, if possible I want to just call a one liner to convert JSON to BSON.

public class CustomDeserializer extends StdDeserializer<ObjectA> { 

   @Override
   public ObjectA deserialize(JsonParser jp, DeserializationContext ctxt)
          throws IOException {
        // Get ArrayNode from JSON
        ArrayNode nodes = jp.getCodec().readTree(jp);

        // Prepare ObjectNode for conversion to BSON
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode rootNode = mapper.createObjectNode();
        ArrayNode newArray = rootNode.putArray("newArray");

        // Iterate through ArrayNode to put into ObjectNode
        for (JsonNode node : nodes) {
            newArray.add(node);
        }

        // Decode ObjectNode document into Bytes
        Document doc = Document.parse(rootNode.toString());
        BasicOutputBuffer buffer = new BasicOutputBuffer();
        BsonWriter writer = new BsonBinaryWriter(buffer);
        codec.encode(writer, doc, EncoderContext.builder().build());
        var bsonBytes = Bytes.copyFrom(buffer.toByteArray());

        return new ObjectA(bsonBytes);
   }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source