如何将ObjectId序列化为JSON?

时间:2014-06-15 14:23:56

标签: java json mongodb jackson jongo

我想将Product类的ObjectId序列化为JSON。我得到了以下JSON:

[{"name":"Play for Java: Covers Play 2","type":"Book","company":"Manning Publications","price":30.0,"imagePath":"public/images/play-for-java.png","rating":4.5,"category":"Computer","author":"Nicolas Leroux","publicationDate":1396224000000,"numPage":320,"_id":539da7a6370882f10d5c2777}]

您可以注意到"_id"没有被正确序列化,它应该是"539da7a6370882f10d5c2777"(带双引号)而不仅仅是539da7a6370882f10d5c2777

因此,我尝试按照以下方式实现自己的ObjectIdSerializer

import java.io.IOException;

import org.bson.types.ObjectId;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class ObjectIdSerializer extends JsonSerializer<ObjectId> {
    @Override
    public void serialize(ObjectId value, JsonGenerator jsonGen,SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jsonGen.writeString(value.toString());
    }
}

它给了我不同的错误:java.lang.String cannot be cast to org.bson.types.ObjectId (through reference chain: models.Book["_id"])

以下是我的Product课程和Book课程:

Product.java

@JsonTypeInfo(use= JsonTypeInfo.Id.CLASS,property="_class")
public class Product {
    @ObjectId @Id
    @JsonSerialize(using = ObjectIdSerializer.class)
    protected String id;
    @JsonProperty("name")
    protected String name;
    @JsonProperty("type")
    protected String type;
    @JsonProperty("description")
    protected String description;
    @JsonProperty("company")
    protected String company;
    @JsonProperty("price")
    protected float price;
    @JsonProperty("imagePath")
    protected String imagePath;
    @JsonProperty("imageName")
    protected String imageName;
    @JsonProperty("rating")
    protected float rating;

    public Product() {
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    // Getters and setters
   ...    

Book.java

public class Book extends Product{

    @JsonProperty("category")
    private String category;
    @JsonProperty("author")
    private String author;
    @JsonProperty("publicationDate")
    private Date publicationDate;
    @JsonProperty("numPage")
    private int numPage;

    public Book() {
    }
    // Getters and setters   
   ...

你能帮我解决一下如何正确序列化ObjectId到JSON?

1 个答案:

答案 0 :(得分:4)

看起来Jackson已经被定制为以特殊方式序列化字符串id字段。这可能是与org.bson库集成的一部分。

问题是您的反序列化器是按ObjectId类型而不是String或普通Object进行参数化的。尝试按如下方式更改它,并从字段声明中删除@ObjectId注释。这是一个例子:

public class ObjectIdSerializer extends JsonSerializer<Object> {
    @Override
    public void serialize(Object value, JsonGenerator jsonGen,SerializerProvider provider) throws IOException {
        jsonGen.writeString(value.toString());
    }
}

您也可以考虑采用the Jackson-Jongo provider class来修复所有类的对象ID序列化。