我想将我的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
...
你能帮我弄清楚如何正确序列化为ObjectId
JSON 吗?