自定义MappingJackson2HttpMessageConverter的objectMapper实现Mongodb自定义序列化与反序列化

来源:互联网 发布:centos安装yum 编辑:程序博客网 时间:2024/05/16 11:31

接上篇文章,这是另一种实现:
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;    }
阅读全文
0 0
原创粉丝点击