springboot jackson custom serialization and deserialization instances

  • 2021-11-24 01:48:31
  • OfStack

Directory jackson Custom Serialization and Desequence Serialization JsonSerializer Last Request http Return Object Desequalization JsonDeserializer Summary 1 springboot Custom Serializer

jackson Custom Serialization and Desequencing

spingmvc uses the httpmessageconverter interface to convert http requests and responses.

If you need to add and customize converters, you can use the HttpMessageConverters class of spring boot; Any ben of HttpMessageConverter that exists in the context is added to the converter list.

If you want to use Jackson to serialize and deserialize json, you might want to write your own JsonSerializer and JsonDeserializer classes. Use the @ JsonComponent annotation of spring boot. Using @ JsonComponent annotation will automatically register with Jackson;

Serialize JsonSerializer

First, inherit JsonSerializer and override Serialize function


@JsonComponent   // This comment automatically sets the  Serialize And Deserializer Register to jackson In the middle. 
public class CustomeJackSon {
    public static class Serialize extends JsonSerializer<Date>{
        @Override
        public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            SimpleDateFormat _format = new SimpleDateFormat("yyyy-mm--dd");
            String _dateStr =  _format.format(date);
            jsonGenerator.writeString(_dateStr);
        }
    } 
}

Then add the annotation @ JsonSerialize on the object property that needs to be serialized (using = CustomeJackSon. Serialize. class)


@JsonSerialize(using = CustomeJackSon.Serialize.class)
    private Date date;

Finally, request http to return the object


User home(User id){
        applicationArguments.getOptionNames();
        User _user = new User();
        _user.setId(1);
        _user.setName(" Zhang 3 Abundance ");
        _user.setDate(new Date());
        return _user;
        //return new Date();
    }

Deserialize JsonDeserializer

First, we inherit the JsonDeserializer class, rewrite the deserialize function, and customize our deserialization logic


@JsonComponent   // This comment automatically sets the  Serialize And Deserializer Register to jackson In the middle. 
public class CustomeJackSon {
    public static class Deserializer extends JsonDeserializer<Date>{
 
        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            String _name = jsonParser.getCurrentName();
            long _ss = jsonParser.getLongValue();
            return null;
        }
    }
}

Then add the @ JsonDeserialize annotation on the deserialized attribute


@JsonDeserialize(using = CustomeJackSon.Deserializer.class)
    private Date date;
 Finally in controller Parameter to use the @RequestBody
@RequestMapping(value = "getValue")
    public String getValue(@RequestBody User user){
        return  "0000000";
    }

The Content-Type requested by the client when requesting the corresponding one needs to be application/json

Summary 1

Need to customize the serialization and deserialization of jackson, need to inherit JsonSerializer and JsonDeserializer classes and override their serialization and deserialization functions;

When serializing, you need to add @ JsonSerialize annotation on the object property to be serialized;

The @ RequestBody annotation is required for the controller parameter during deserialization, the @ JsonDeserialize annotation is used for the object property to be deserialized, and the Content-Type requested by the client needs to be application/json

springboot Custom Serializer


@SpringBootConfiguration
public class WebConfig extends WebMvcConfigurationSupport {
    /**
     *  Custom serializer 
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        final MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        // Long->String
        final ToStringSerializer toStringSerializer = new ToStringSerializer(Long.class);
        // date-> pattern format
        final DateSerializer dateSerializer = new DateSerializer(false, new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(toStringSerializer);
        simpleModule.addSerializer(dateSerializer);
        jackson2HttpMessageConverter.getObjectMapper().registerModule(simpleModule);
        converters.add(jackson2HttpMessageConverter);
        super.configureMessageConverters(converters);
    }
}

Related articles: