[JAVA-2869] Encoding enums via codecs Created: 29/May/18  Updated: 11/Sep/19  Resolved: 11/Dec/18

Status: Closed
Project: Java Driver
Component/s: Codecs
Affects Version/s: 3.7.0
Fix Version/s: None

Type: Task Priority: Critical - P2
Reporter: richi arora Assignee: Unassigned
Resolution: Done Votes: 0
Labels: test
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

I have a package "com.test"

It has 2 classes:

 

public class Employee {
 
private String name;
 
private String id;
 
private Long age;
 
private Currency salaryCurrency;
 
private Double pay;
 
private isActive;
 
private Type type = Type.CONTRACT;
 
//getter setters
 
}

 

public enum Type {
 
CONTRACT,PERMANENT;
 
}

 

When I try to encode I get no codec found for Type.

PS i created custom CurrencyCodec

 
Employee emp = new Employee();
emp.setType(Type.PERMANENT);
emp.setAge(30);
emp.setName("TestUser");
PojoCodecProvider builder = PojoCodecProvider.builder().conventions(Conventions
        .DEFAULT_CONVENTIONS)
        .automatic(false).register("com.test").build();
CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(fromProviders(builder),
        fromCodecs(new LongCodec(),new CurrencyCodec(),
                new StringCodec(), new DateCodec(), new BooleanCodec(), new DoubleCodec()));
emp.setId(UUID.randomUUID().toString());
Codec<Employee> st = builder.get(Employee.class,pojoCodecRegistry);
BsonDocument doc = new BsonDocument();
st.encode(new BsonDocumentWriter(doc),emp, EncoderContext.builder().isEncodingCollectibleDocument(true).build
        ());



 Comments   
Comment by Ross Lawley [ 11/Dec/18 ]

Hi richiarora,

You should be using the CodecRegistry and not the PojoCodecProvider to encode the document. I would also recommend including the MongoClient.getDefaultCodecRegistry() as the final fallback registry to ensure you have Codecs for all the default types.

Just to let you know for future reference this project is for Java driver bugs or feature requests. The best place for questions regarding MongoDB usage or the Java driver specifics is the mongodb-user mailinglist or stackoverflow as you will reach a broader audience there. If your business requires an answer from MongoDB within a time frame then we do offer production support.

If you do follow up via one of the options above please post a link and I will follow the conversation there.

Ross

Generated at Thu Feb 08 08:58:16 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.