繁体   English   中英

Spring Boot HttpMessageNotReadableException

[英]Spring Boot HttpMessageNotReadableException

我有这个课程来代表一个用户:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
public class UserDto implements Serializable {
    private Long id;
    private String username;
    private String email;
    private String password;
    private Collection<? extends GrantedAuthority> roles;

    public UserDto() {
    }
}

}

我正在尝试做的是让Spring将下面控制器的@RequestBody映射到UserDto:

public class AuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private AuthService authService;

    @RequestMapping(value = "signup", method = RequestMethod.POST)
    public ResponseEntity<?> addUser(@RequestBody UserDto userDto) throws Exception {
        UserDto existingUserDto;

        try {
            existingUserDto = userService.save(userDto);
        } catch (Exception e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<>(existingUserDto, HttpStatus.CREATED);
    }
}

但是,当我尝试发送Post请求时,我从Spring得到以下错误:

Failed to read HTTP message:                 org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'username': was expecting ('true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@2c477da6; line: 1, column: 10]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'username': was expecting ('true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@2c477da6; line: 1, column: 10]

我试图做的是声明一个自定义MappingJackson2HttpMessageConverter,但没有得到任何不同的结果

@Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        jsonConverter.setObjectMapper(objectMapper);
        return jsonConverter;
    } 

这是我正在执行的请求的屏幕(Content-Type:application / json):

邮递员要求

你有什么主意吗?

您能否将控制器方法@RequestMapping更改为以下内容。

@RequestMapping(value = "", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })

另外,您无需添加自定义MappingJackson2HttpMessageConverter即可完成此操作,还请确保在控制器中标注了正确的请求映射。

@Controller
@RequestMapping("/api/users")

还要在模型类中删除以下注释。 将getter和setter添加到所有属性,同时保留默认构造函数。

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter

希望这可以帮助。 编码愉快!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM