0

我想将我的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班级:

产品.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
   ...    

图书.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   
   ...

你能帮我弄清楚如何正确序列化为ObjectIdJSON 吗?

4

1 回答 1

4

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

问题是您的反序列化器是由ObjectIdtype 而不是String或 plain参数化的Object。尝试如下更改它,并@ObjectId从字段声明中删除注释。这是一个例子:

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

您还可以考虑采用Jackson-Jongo 提供程序类来修复所有类的对象 ID 序列化。

于 2014-06-15T18:30:41.907 回答