Jackson Mapper序列化/反序列化ObjectId [英] Jackson Mapper Serialize/Deserialize ObjectId
问题描述
我的POJO是:
import org.jongo.marshall.jackson.id.Id;
public class User {
@Id
private String id;
private String name;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
我从mongo数据库获取用户并希望输出他使用jackson mapper进入文件
I get user from mongo database and want to output him into a file with jackson mapper
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValue(new File("c:/user.txt"), user);
我在我的档案中得到这样的东西
and I get something like this in my file
{
"name" : "John",
"age" : 23,
"_id" : {
"time" : 1358443593000,
"inc" : 660831772,
"machine" : 2028353122,
"new" : false,
"timeSecond" : 1358443593
}
}
我需要将id字段作为字符串存储到文件中,因为当我反序列化此对象时我在pojo中的id字段看起来像这样
I need id field to be stored into a file as string because when i deserialize this object my id field in pojo looks something like this
{time:1358443593000,inc:660831772,machine:2028353122,new:false, timeSecond:1358443593}
{"time":1358443593000,"inc":660831772,"machine":2028353122,"new":false,"timeSecond":1358443593}
任何帮助都是apreciated
Any help will be apreciated
推荐答案
回答我自己的问题。找到解决方案 Spring 3.2和Jackson 2:添加自定义对象映射器
Answering my own question. Found solution here Spring 3.2 and Jackson 2: add custom object mapper
我需要自定义对象映射器和ObjectId序列化器。
I needed custom object mapper and ObjectId serializer.
public class ObjectIdSerializer extends JsonSerializer<ObjectId> {
@Override
public void serialize(ObjectId value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(value.toString());
}
}
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
SimpleModule module = new SimpleModule("ObjectIdmodule");
module.addSerializer(ObjectId.class, new ObjectIdSerializer());
this.registerModule(module);
}
}
这篇关于Jackson Mapper序列化/反序列化ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!