我的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数据库获取用户,并希望将其输出到具有杰克逊映射器的文件中
ObjectMapper mapper = new ObjectMapper(); mapper.writerWithDefaultPrettyPrinter().writeValue(new File("c:/user.txt"),user);
我的文件中有这样的东西
{ "name" : "John","age" : 23,"_id" : { "time" : 1358443593000,"inc" : 660831772,"machine" : 2028353122,"new" : false,"timeSecond" : 1358443593 } }
我需要id字段作为字符串存储到一个文件中,因为当我反序列化这个对象时,我的pojo中的id字段看起来像这样
{ “时间”:1358443593000,“公司”:660831772,“机器”:2028353122,“新”:假的,“timeSecond”:1358443593}
任何帮助将被解除
解决方法
回答我自己的问题找到解决方案
Spring 3.2 and Jackson 2: add custom object mapper
我需要自定义对象映射器和ObjectId序列化程序.
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); } }