记jsonstr转bean问题

1.springboot中 使用hutool的 JSONUtil.toBean(resultStr,YBResponse.class);

时当str中有内嵌对象有空值时会有转换问题出现jsonnull报错

解决方式 使用alibaba 的JSONObject.parseObject(resultStr,MedicalResponse.class);

2.空值null如果想变成""输出到前端可以直接使用以下方式

package com.newland.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });

        return objectMapper;
    }
}


版权声明:本文为bazheling原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。