mappingjackson2httpmessageconverter не может обработать нулевое значение - PullRequest
0 голосов
/ 04 февраля 2020

1 контроллер

@GetMapping("/{id}")
@ResponseBody
public Object findById(@PathVariable String id) {
    return service.findById(id); // here return null
}

2 MappingJackson2HttpMessageConverter

public class MyMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
    private static final MediaType TEXT_EVENT_STREAM = new MediaType("text", "event-stream");
    private PrettyPrinter ssePrettyPrinter;

    @Override
    protected void init(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
        if(this.objectMapper != null) {
            this.objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX,true);
        }
        setDefaultCharset(DEFAULT_CHARSET);
        DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
        prettyPrinter.indentObjectsWith(new DefaultIndenter("  ", "\ndata:"));
        this.ssePrettyPrinter = prettyPrinter;
    }

    @Override
    protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {

        MediaType contentType = outputMessage.getHeaders().getContentType();
        JsonEncoding encoding = getJsonEncoding(contentType);
        JsonGenerator generator = this.objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
        try {
            writePrefix(generator, object);

            Class<?> serializationView = null;
            FilterProvider filters = null;
            Object value = object;
            JavaType javaType = null;
            if (object instanceof MappingJacksonValue) {
                MappingJacksonValue container = (MappingJacksonValue) object;
                value = container.getValue();
                serializationView = container.getSerializationView();
                filters = container.getFilters();
            } else if(!(object instanceof BaseObj2JsonResponse)){
                BaseObj2JsonResponse boj = new BaseObj2JsonResponse();
                if(object instanceof IResultCode) {
                    boj.setResultCode((IResultCode)object);
                } else if (object instanceof ObjectError) { 
                    boj.setCode(IResultCode.DEFAULT_CODE.ERROR.getCode());
                    boj.setMessage(((ObjectError)object).getDefaultMessage());
                } else {                
                    boj.setResultCode(IResultCode.DEFAULT_CODE.SUCCESS);
                    if(object instanceof PageMybatis) {
                        boj.setContent(((PageMybatis<?>)object).toPageObj());
                    } else {
                        boj.setContent(object);
                    }
                }
                value = boj;
            }
            if (type != null && value != null && TypeUtils.isAssignable(type, value.getClass())) {
                javaType = getJavaType(type, null);
            }
            ObjectWriter objectWriter;
            if (serializationView != null) {
                objectWriter = this.objectMapper.writerWithView(serializationView);
            } else if (filters != null) {
                objectWriter = this.objectMapper.writer(filters);
            } else {
                objectWriter = this.objectMapper.writer();
            }
            if (javaType != null && javaType.isContainerType()) {
                objectWriter = objectWriter.forType(javaType);
            }
            SerializationConfig config = objectWriter.getConfig();
            if (contentType != null && contentType.isCompatibleWith(TEXT_EVENT_STREAM)
                    && config.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
                objectWriter = objectWriter.with(this.ssePrettyPrinter);
            }
            objectWriter.writeValue(generator, value);

            writeSuffix(generator, object);
            generator.flush();

        } catch (JsonProcessingException ex) {
            throw new HttpMessageNotWritableException("Could not write content: " + ex.getMessage(), ex);
        }
    }
}

3 BaseObj2JsonResponse

public class BaseObj2JsonResponse {
    private Integer code = 0; 
    private String message; 
    private Object content;
}

Я определил класс BaseObj2JsonResponse для равномерной обработки возврата контроллера, но если контроллер возвращает ноль, MappingJackson2HttpMessageConverter не может обработать результат.

org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.canWrite(Class<?>, MediaType) имеет значение false, поскольку com.fasterxml.jackson.databind.ser.impl.ReadOnlyClassToSerializerMap.untypedValueSerializer(Class<?>) возвращает com.faster xml .jackson.databind.ser.impl.UnknownSerializer

...