spring(1) spring-json global serialization

Keywords: Programming Java JSON Spring SpringBoot

Scenario introduction

Background transmission of data to the front end, generally using json, not to mention many, see an example:

If you use the mongodb database, it's very easy to have a situation, which happens when you transfer ObjectId (the default data can be the primary key):

  data :{
    objectId :{
        timestamp: 123123123,
        machineIdentifier: 12,
        processIdentifier: 12,
        counter:5 6,
    },
    name:"Zhang San
  }

The problem arises. The front end of ObjectId just wants us to say pass a string (ObjectId), while we pass an object, the front end will certainly (you know!!! )

Solutions

Mode 1: Annotations added

  1. Write a json serialized class for ObjectId and rewrite the serialized function
public class ObjectIdSerializer extends JsonSerializer<ObjectId> {
    
    @Override
    public void serialize(ObjectId value, JsonGenerator jsonGen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jsonGen.writeString(value.toString());
    }
}
  1. Annotate the properties of ObjectId in the java class you need to export as follows:
Class User{
    @JsonSerialize(using = ObjectIdSerializer.class)
    private ObjectId id;
    private String name;
}

Advantage: Problem solving < br > Disadvantage: Whatever is passed to the front end of the project needs to be annotated.

Mode 2: Global configuration

The global configuration is based on the first step of the method. The specific operations are as follows:

  1. Create a custom ObjectMapper class, as follows:
@SuppressWarnings("serial")
public class ObjectIdMapper extends ObjectMapper {
    
    public ObjectIdMapper() {
        SimpleModule module = new SimpleModule("ObjectIdmodule");
        module.addSerializer(ObjectId.class, new ObjectIdSerializer());
        this.registerModule(module);
    }

}
  1. For the ssm project, add the following configuration to the spring configuration file (just configure beans directly for the spring boot project):
<bean id="mappingJackson2HttpMessageConverter"
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>text/html;charset=UTF-8</value>
        </list>
    </property>
    <!-- <property name="objectMapper">
         <bean class="com.ftf.clw.dsc.web.convert.ObjectIdMapper"></bean>
     </property> -->
</bean>

3) springboot project, just add a configuration bean directly. The configuration is as follows

@Configuration
public class JsonMessageConverter {

    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder){
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        //Convert null of json attribute to null string
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                gen.writeString("");
            }
        });

        SimpleModule module = new SimpleModule();
        module.addSerializer(ObjectId.class, new ObjectIdSerializer());
        objectMapper.registerModule(module);
        return objectMapper;
    }
}

test result

   data :{
    objectId :"jjaiaiajiaiaiajaldkdkdkdkdkdkdd",
    name: "Zhang San"
  } 

Bottom analysis

Using java serialized open source jar, Jackson < br >

jackson.See Synonyms at jackson <br> springboot changed the serialization tool Jackson to FastJson <br>

Posted by jdesilva on Thu, 31 Jan 2019 11:36:16 -0800