Rename ObjectId _id to id in jackson deserialization with Jongo and MongoDB

后端 未结 4 1103
夕颜
夕颜 2020-12-21 05:56

I\'ve just started working on a project using the play framework,jongo and MongoDB. The project was initially written in Play 2.1 with pojos with an String id field annotat

相关标签:
4条回答
  • 2020-12-21 06:20

    ObjectIdSerializer always writes property mapped with @ObjectId to a new instance of ObjectId. This is wrong when you map this property to a String.

    To avoid this behaviour, I've write a NoObjectIdSerializer :

    public class NoObjectIdSerializer extends JsonSerializer<String> {
        @Override
        public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
            jgen.writeString(value);
        }
    }
    

    used like this :

    @ObjectId
    @JsonSerialize(using = NoObjectIdSerializer.class)
    protected final String _id;
    

    There is an open issue.

    0 讨论(0)
  • 2020-12-21 06:24

    I think that there is an annotation in jackson that allows you to change the property name, I think is : @JsonProperty but you can see all the possible annotations in this link:

    https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations

    I hope this solve your problem

    0 讨论(0)
  • 2020-12-21 06:26

    You can try using @JsonValue, Jongo does not seem to use them, but without any response from the developers this behaviour might be subject to change in future releases.

    @JsonValue
    public Map<String, Object> getJson() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("id", id);
        return map;
    }
    

    The more proper solution would be to try combining @JsonView with @Id annotation
    Remember to specify which View to use on Jongo's ObjectMapper and your Jackson ObjectMapper (the one to use in REST layer, I presume)

    @Id
    @JsonView(Views.DatabaseView.class)
    private String id;
    
    @JsonView(Views.PublicView.class)
    public String getId() {
        return id;
    }
    
    0 讨论(0)
  • 2020-12-21 06:26

    The Jongo's behaviour has changed since 1.1 for a more consistent handling of its owns annotations.

    If your '_id' is a String and you want this field to be stored into Mongo as a String then only @Id is needed.

    @Id + @ObjectId on a String property means :

    "My String property named 'foo' is a valid ObjectId. This property has to be stored with the name '_id' and have to be handled as an ObjectId."

    0 讨论(0)
提交回复
热议问题