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
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.
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
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;
}
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."