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
388 views
in Technique[技术] by (71.8m points)

java - converting Document objects in MongoDB 3 to POJOS

I'm saving an object with a java.util.Date field into a MongoDB 3.2 instance.

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(myObject);
collection.insertOne(Document.parse(json));

the String contains:

"captured": 1454549266735

then I read it from the MongoDB instance:

    final Document document = collection.find(eq("key", value)).first();
    final String json = document.toJson();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    xx = mapper.readValue(json, MyClass.class);

the deserialization fails:

java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.Date out of START_OBJECT token

I see that the json string created by "document.toJson()" contains:

"captured": {
    "$numberLong": "1454550216318"
}

instead of what was there originally ("captured": 1454549266735) MongoDB docs say they started using "MongoDB Extended Json". I tried both Jackson 1 and 2 to parse it - no luck.

what is the easiest way to convert those Document objects provided by MongoDB 3 to Java POJOs? maybe I can skip toJson() step altogether?

I tried mongojack - that one does not support MongoDB3.

Looked at couple other POJO mappers listed on MongoDB docs page - they all require putting their custom annotations to Java classes.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You should define and use custom JsonWriterSettings to fine-tune JSON generation:

 JsonWriterSettings settings = JsonWriterSettings.builder()
         .int64Converter((value, writer) -> writer.writeNumber(value.toString()))
         .build();

 String json = new Document("a", 12).append("b", 14L).toJson(settings);

Will produce:

 { "a" : 12, "b" : 14 }

If you will not use custom settings then document will produce extended json:

 { "a" : 12, "b" : { "$numberLong" : "14" } }

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

...