Reputation: 63
I have this class to represent a User:
@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() {
}
}
}
What I'm trying to do is to let Spring map @RequestBody of the controller below to a 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);
}
}
But instead what when I try to send a Post request I get the following error from 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]
What I tried to do was declaring a custom MappingJackson2HttpMessageConverter but I didn't get any different result
@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;
}
Here a screen of the requested I'm doing ( with Content-Type: application/json):
Do you have any idea?
Upvotes: 1
Views: 21243
Reputation: 21124
Could you please change your controller method @RequestMapping
to the following.
@RequestMapping(value = "", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
Also you don't need to add a a custom MappingJackson2HttpMessageConverter
to get this thing done.Also make sure you have correct request mapping annotated in your controller.
@Controller
@RequestMapping("/api/users")
Also remove the following annotations in your model class. Add getters and setters to all the properties while keeping the default constructor.
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
Hope this helps. happy coding !
Upvotes: 1