2

I am using mongo-java-driver in my application to read and write data to mongodb.

I have classes like this -

public A{
    private String a;
    //Getters & Setters
}

public class B{
    private String b;
    private List<A> a;
    //Getters & Setters
}

public class C{
    private String c;
    private B b;
    //Getters & Setters
}

I have created Codec for the classes C like this -

public class CCodec implements Codec<C> {

    private Codec<Document> documentCodec;

    public CCodec(CodecRegistry registry) {
        documentCodec = registry.get(Document.class);
    }

    @Override
    public void encode(BsonWriter writer, C c, EncoderContext context)     {
        Document document = new Document();
        document.put("c",c.getC());
        document.put("b",c.getB());
        documentCodec.encode(writer, document, context);
    }
}

Codec for class B -

public class BCodec implements Codec<B> {

        private Codec<Document> documentCodec;

        public CCodec(CodecRegistry registry) {
            documentCodec = registry.get(Document.class);
        }

        @Override
        public void encode(BsonWriter writer, B b, EncoderContext context)     {
            writer.writeStartDocument();
            writer.writeString("b",b.getB());
            //How to encode A Here
            writer.writeEndDocument();
        }
    }

I can not do encoding in BCodec as i did for CCodec because when i say

Document document = new Document();

It creates a new document but i wan't to have it embedded in Document C.

Now the question is how do i encode field a of type List in B class? See encode method of BCodec class. Needless to say i have added all the Codec in CodecProvider.

Any help is appreciated.

1 Answer 1

1

You can try using the DocumentCodec.encode method as follows -

@Override
public void encode(BsonWriter writer, B b, EncoderContext context) {
    org.bson.Document bsonDocument = new org.bson.Document();
    List<A> a = B.getA();
    bsonDocument.put("a", a);
    ...
    documentCodec.encode(writer, bsonDocument, encoderContext);
}

and as you decode :

@Override
public B decode(BsonReader reader, DecoderContext decoderContext) {
    org.bson.Document bsonDocument = documentCodec.decode(reader, decoderContext);
    B b = new B();
    b.setA((List)bsonDocument.getString("a"));
    ...
    return b;
}
Sign up to request clarification or add additional context in comments.

2 Comments

How is it different from one i have written above?
@RaviKumar //How to encode A Here in your code is what has been answered. how do i encode field a of type List in B class? is where I have casted the encoded A to a List while decoding the B.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.