Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

json - Jackson Mapper Serialize/Deserialize ObjectId

My POJO is :

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;
    }
}

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
    }
}

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}

Any help will be apreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Answering my own question. Found solution here Spring 3.2 and Jackson 2: add custom object mapper

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);
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...