1. 程式人生 > >SpringBoot的json序列化及時間序列化處理

SpringBoot的json序列化及時間序列化處理

urn G1 public nwr port 方法 als 前後臺 nconf

使用場景:前臺的多種時間格式存入後臺,後臺返回同時的時間格式到前臺。

1 在config目錄下配置jscksonConfig.java

package com.test.domi.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Date; /** * 時間序列化 */ public class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean
public ObjectMapper jacksonOnjectMapper(Jackson2ObjectMapperBuilder builder){ ObjectMapper objectMapper = builder.createXmlMapper(false).build(); //將json屬性的空值null轉化為空字符串"" objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException, JsonProcessingException { arg1.writeString(""); } }); //json轉換日期格式設置 objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); SimpleModule simpleModule = new SimpleModule(); //在進出前後臺的時候,設置BigDecimal和字符串之間轉換 simpleModule.addSerializer(BigDecimal.class,ToStringSerializer.instance); //設置對前臺傳入的多種格式的時間都支持序列化 simpleModule.addDeserializer(Date.class,CommonDateDeserializer.INSTANCE); objectMapper.registerModule(simpleModule); return objectMapper; } }

二 在config目錄下CommonDateDeserializer繼承stdScalarDeserializer序列化類,重寫deserialize序列化設置方法
package com.test.domi.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import org.apache.commons.lang.time.DateUtils;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

public class CommonDateDeserializer extends StdScalarDeserializer {

    public  static final CommonDateDeserializer INSTANCE = new CommonDateDeserializer(Date.class);
    private final String[] DATE_FORMAT_STRS = {"yyyy-MM-dd","yyyy/MM/dd"};

    protected CommonDateDeserializer(Class vc) {
        super(vc);
    }

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        JsonToken t = jsonParser.getCurrentToken();
        if (t == JsonToken.VALUE_STRING) {
            String str = jsonParser.getText().trim();
            if (str.length() == 0) {
                return getEmptyValue(deserializationContext);
            }
            try {
                return DateUtils.parseDate(str,DATE_FORMAT_STRS);
            } catch (ParseException e) {
                return (java.util.Date)deserializationContext.handleWeirdStringValue(handledType(),str,"expected format \"%s\"");
            }
        }

        if (t == JsonToken.START_ARRAY && deserializationContext.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) {
            jsonParser.nextToken();
            final Date parsed = _parseDate(jsonParser,deserializationContext);
            t = jsonParser.nextToken();
            if (t != JsonToken.END_ARRAY) {
                handleMissingEndArrayForSingle(jsonParser,deserializationContext);
            }
            return parsed;
        }
        return super._parseDate(jsonParser,deserializationContext);
    }
}

SpringBoot的json序列化及時間序列化處理