Jackson Mapper序列化/反序列化ObjectId

时间:2013-01-17 22:19:31

标签: json jackson

我的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的文件

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 “INC”:660831772, “机器”:2028353122, “新”:假 “timeSecond”:1358443593}

任何帮助都将是apreciated

1 个答案:

答案 0 :(得分:14)

回答我自己的问题。在此找到解决方案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);
    }

}