springboot ObjectId 序列化 反序列化

springboot ObjectId 序列化,反序列化

1. 涉及方法和注解:

@RequestBody

@ResponseBody

objectMapper.readValue()

objectMapper.writeValueAsString()

2. 配置类

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.io.IOException;

@Configuration
public class JacksonConfig implements InitializingBean {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void afterPropertiesSet() {
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(ObjectId.class, ToStringSerializer.instance);
        simpleModule.addDeserializer(ObjectId.class, new ObjectIdDeserializer());
        objectMapper.registerModule(simpleModule);
    }

    public class ObjectIdDeserializer  extends JsonDeserializer {
        @Override
        public ObjectId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            return new ObjectId(p.getText());
        }
    }
}

你可能感兴趣的:(spring,boot,spring,boot,mongodb,反序列化,序列化,ObjectId)