Spring Boot HttpMessageNotReadableException

时间:2017-02-01 02:17:34

标签: java spring spring-boot

我有这个类代表用户:

@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):

PostMan Request

你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

请您将控制器方法@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

希望这会有所帮助。快乐的编码!