ylemoigne/mongo-jackson-codec

Object marshalling is failing during Object -> JSON conversion

Closed this issue · 6 comments

gdrte commented

Spring Object mapper is failing during JSON marshalling saying "BsonSerializer can only be used with BsonGenerator". This is because of @id annotation. The same serializer being used in JsonGenerator context. Please advise if there is any workaround.

Thanks

Hi,

Can you provide me a gist/test case ?

gdrte commented

Sorry for the late response.. Here it is.

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import fr.javatic.mongo.jacksonCodec.objectId.Id;
import lombok.Data;
import org.bson.types.ObjectId;
import org.junit.Assert;
import org.junit.Test;

public class JsonConversionTest {

    @Data
    public class FailedTest {
        @Id
        String id = new ObjectId().toHexString();
        String name="Test";


    }

    @Test
    public void failedToJSONTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        mapper.writeValueAsString(new FailedTest());
        System.out.println("I never reach, because mapper throws exception :(");
    }


    @Data
    public class PassedTest {

        String id = new ObjectId().toHexString();
        String name="See I have no @Id";
    }

    @Test
    public void passedToJSONTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        String str=mapper.writeValueAsString(new PassedTest());
        Assert.assertTrue(str.indexOf("@Id")>0);
    }

}

No problem for delay in response.

I dont understand what you're trying to achieve. As shown in the README, the goal of this project is to provide a codec for the mongo driver.

So the ObjectMapper is not intended to be used directly but through the mongo codec registry.
Then you can use the codec with the mongo client (example in the README), or directly as shown in the unit test in https://github.com/ylemoigne/mongo-jackson-codec/blob/master/src/test/java/fr/javatic/mongo/jacksonCodec/JacksonCodecTest.java

gdrte commented

I am sorry, I didn't convey my intention. What I am trying to achieve is, I want to use the same model as a json response. I understand the scope of this project, it perfectly does its intended purpose. But I am loosing the ability to use the model as my response object. The spring-boot objectmapper fails to convert the object to json. If this functionality is beyond the scope of this project, we can close this. By the way Morphia also have a similar @id annotation. But it works in both scenarios from/to bson/json.

Thanks

Sorry, It took me some time to understand your issue...
I just published a 0.4 release which should fix the issue. Can you confirm it ?

gdrte commented

Its working, thank you very much.