Springboot接收前端的Json但是为null问题
作者:无相孤君
这篇文章主要介绍了Springboot接收前端的Json但是为null问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教<BR>
Springboot接收前端的Json但是为null
接收前端传过来的Json,
{ "id": 94, "nickname": "王明", "username": "萧强", "password": "nulla", "email": "p.tplfsayobt@qq.com", "avatar": "http://dummyimage.com/100x100", "type": 47, "createTime": "2007-12-03 08:23:55", "updateTime": "1972-02-26 05:02:56" }
然后反序列化转化成User实体类,打印实体类为空,仔细检查了一下。
@PostMapping(value = "/register") public Result registerUser(User user) { userService.register(user); return ResultGenerator.getSuccessResult(user); }
少了@RequestBody注解
@PostMapping(value = "/register") public Result registerUser(@RequestBody User user) { userService.register(user); return ResultGenerator.getSuccessResult(user); }
现在实体类就有数据了。
Springboot将返回前端的null值变为固定值
做了个项目 当我给前端返回null值时需求要把 null值都返回成 “–” 记录一下子
在springboot上配置一下就好
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; /** * @author : Nan * @date : 2021/06/20 * @description : */ @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, IOException { // 这里可以给任意值 将返回null的值替换 但是目前不知道还想返回null怎么办 jsonGenerator.writeString("--"); } }); return objectMapper; } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。