일단 Spring 4에 내장된 jackson2 를 그대로 활용한다는 가정하에 기술한다.
NullSerializer 작성
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
/**
* jackson > Object의 null값을 "null" 문자열 대신 ""로 출력할 수 있도록 설정
*/
public class NullSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString("");
}
}
NumberToStringSerializer 작성 (꼭 필요한지는 잘...)
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
/**
* jackson > Number의 null값을 "null" 문자열 대신 ""로 출력할 수 있도록 설정
*/
public class NumberToStringSerializer extends JsonSerializer<Number> {
@Override
public void serialize(Number value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if(value == null){
gen.writeString("");
}else {
gen.writeString(value.toString());
}
}
}
CustomObjectMapper 작성
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
/**
* json serialize 규칙을 재정의하기 위해 작성한 object mapper
*/
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Number.class, new NumberToStringSerializer()); // 숫자타입 null => "" 로
this.registerModule(simpleModule);
this.getSerializerProvider().setNullValueSerializer(new NullSerializer()); // Object null => "" 로
// this.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); //마샬링시 빈 값을 생략하는 옵션 (사용할지 추후 검토)
this.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); // 외따욤표 허용
this.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// springboot 기본 설정
this.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
this.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
}
spring-servlet.xml
<!-- json serialize 규칙을 재정의하기 위해 작성한 object mapper -->
<bean id="customObjectMapper" class="codegurus.cmm.config.json.CustomObjectMapper" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
...
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<constructor-arg ref="customObjectMapper" />
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
...
</bean>