Skip to content
This repository

Wrong (un)marshalling when ObjectId is not annotated with JSonProperty #33

Closed
bguerout opened this Issue April 27, 2012 · 2 comments

1 participant

Benoit Guérout
Benoit Guérout
Owner

As described in th documentation, a POJO with an ObjectId named '_id' doesn't need to be annotated with JSONProperty

Given a POJO :

    public static class User {
        private ObjectId _id;
        private String name;

        public ObjectId getId() {
            return id;
        }

        public void setId(ObjectId _id) {
            this.id = _id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

Jackson handle '_id' and getId() as two different properties.
User is serialised as { "_id" : "4f92d1ae44ae2dac4527d49b" , "name" : "johnny" , "id" : { "$oid" : "4f92d1ae44ae2dac4527d49b"}}
During deserialization, Jackson sets '_id' property with ''_id" field and tries to set 'id' property using a new ObjectId()

Benoit Guérout
Owner

Test to reproduce bug :

public class Issue33Test {

    private MongoCollection collection;

    @Before
    public void setUp() throws Exception {
        Mongo mongo = new Mongo();
        DB db = mongo.getDB("tests");
        collection = new Jongo(db).getCollection("Users");
    }

    @After
    public void tearDown() throws Exception {
        collection.drop();
    }

    @Test
    public void canRemoveCustomObjectId() throws Exception {

        //given
        User user = new User();
        ObjectId customId = new ObjectId("4f92d1ae44ae2dac4527d49b");
        user.setId(customId);
        user.setName("johnny");

        //when
        collection.save(user);
        User result = collection.findOne("{}").as(User.class);

        //then
        assertThat(result.getId()).isEqualTo(customId);
    }

    public static class User {


        private ObjectId _id;
        private String name;

        public ObjectId getId() {
            return _id;
        }

        public void setId(ObjectId _id) {
            this._id = _id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
Benoit Guérout
Owner

Jackson handles _id property and getId() method as two differents values.
An ObjectIdDeserializer is missing and Jackson is not able to inject a valid ObjectId through setId(...)

Benoit Guérout bguerout closed this in 94fefdd May 03, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.