我有一个接受ObjectNode
as的控制器@RequestBody
。
这ObjectNode
代表json
了一些用户数据
{
"given_name":"ana",
"family_name": "fabry",
"email": "fabry@gmail.com",
"password": "mypass",
"gender": "FEMALE"
}
控制器.java
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public JsonNode createUser(@RequestBody ObjectNode user){
return userService.addUser(user);
}
我想让用户ObjectNode
将其转换为 JavaPOJO
将其保存到数据库并再次将其返回为JsonNode
.
UserServiceImpl.java
private final UserRepository userRepository;
private final UserMapper userMapper;
@Override
public JsonNode addUser(@RequestBody ObjectNode user) {
try {
return userMapper.fromJson(user)
.map(r -> {
final User created = userRepository.save(r);
return created;
})
.map(userMapper::toJson)
.orElseThrow(() -> new ResourceNotFoundException("Unable to find user"));
} catch (RuntimeException re) {
throw re;
}
}
转换ObjectNode
为POJO
我在UserMapper
课堂上这样做了:
public Optional<User> fromJson(ObjectNode jsonUser) {
User user = objectMapper.treeToValue(jsonUser, User.class);
}
另外,为了写对象,JsonNode
我这样做了:
public JsonNode toJson(User user) {
ObjectNode node = objectMapper.createObjectNode();
node.put("email", user.email);
node.put("password", user.password);
node.put("firstName", user.firstName);
node.put("lastName", user.firstName);
node.put("gender", user.gender.value);
node.put("registrationTime", user.registrationTime.toString());
return node;
}
用户.java
@Document(collection = "user")
@Builder
@AllArgsConstructor
public class User {
@Indexed(unique = true)
public final String email;
@JsonProperty("password")
public final String password;
@JsonProperty("firstName")
public final String firstName;
@JsonProperty("lastName")
public final String lastName;
@JsonProperty("gender")
public final Gender gender;
@JsonProperty("registrationTime")
public final Instant registrationTime;
public static User createUser(
String email,
String password,
String firstName,
String lastName,
Gender gender,
Instant registrationTime){
return new User(email, password, firstName, lastName, gender, registrationTime);
}
}
当我运行我的应用程序时,这是我收到的错误:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.domain.User` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
我已经阅读了有关该错误的信息,并且似乎发生此错误是因为 Jackson 库不知道如何创建一个没有空构造函数的模型,并且该模型包含一个带有参数的构造函数,我用@JsonProperty("fieldName")
. 但即使在申请后,@JsonProperty("fieldName")
我仍然遇到同样的错误。
我已将 ObjecatMapper 定义为 Bean
@Bean
ObjectMapper getObjectMapper(){
return new ObjectMapper();
}
我在这里想念什么?