接上篇文章,这是另一种实现:
1.spring mvc 配置文件里:
<bean id="myobjectMapper" class="com.converter.MyObjectMapper" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="myobjectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
2.自定义的myobjectMapper:
public class MyObjectMapper extends ObjectMapper {
public MyObjectMapper() {
SimpleModule se = new SimpleModule();
se.addSerializer(ObjectId.class, new ObjectIdSerializer());
se.addDeserializer(Document.class, new DocumentDeserializer());
this.registerModule(se);
}
private class ObjectIdSerializer extends JsonSerializer<ObjectId> {
@Override
public void serialize(ObjectId arg0, JsonGenerator arg1, SerializerProvider arg2)
throws IOException, JsonProcessingException {
System.out.println("序列化,进来了。");
System.out.println(arg1.toString());
if(arg0 == null) {
arg1.writeNull();
} else {
arg1.writeString(arg0.toString());
}
}
}
private class DocumentDeserializer extends JsonDeserializer<Document> {
public Document deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
System.out.println("Document反序列化进来了");
JsonNode node = p.getCodec().readTree(p);
String docstr = node.toString();
String oid = node.get("_id").asText();
System.out.println("node.toString--->"+ docstr);
docstr = docstr.replace("\""+oid+"\"","{ \"$oid\" : \""+oid+"\" }");
System.out.println("转换后的node.toString--->"+docstr);
return Document.parse(docstr);
}
}
}
3.controller层接收、返回document的json数据就可以直接用对象了:
public Document findOne(@RequestBody Document document) throws Exception{
System.out.println("传进来的Document-->"+document);
System.out.println("传进来的Document.toJson--->"+document.toJson());
String collection = "hos_user_info";
String id = "598da5dd3888f020b164b25f";
Document doc = service.queryById(collection, id);
System.out.println("findOne(),doc.toString---->"+doc);
System.out.println("findOne(),doc.toJson()---->"+doc.toJson());
logger.info("findOne(),doc.toString---->{}",doc);
logger.info("findOne(),doc.toJson()---->{}",doc.toJson());
return doc;
}