【发布时间】:2020-07-20 19:04:48
【问题描述】:
首先,当我得到User 实体时,我试图阻止 JSON 中的递归。为此,我在User 类中添加了@JsonIdentityInfo 注释。它在序列化时按预期工作(当我得到 User 时),但在反序列化时(在注册 User 时)Jackson 会返回:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: No Object Id found for an instance of `.entity.User`, to assign to property 'id'; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: No Object Id found for an instance of `.entity.User`, to assign to property 'id'
at [Source: (PushbackInputStream); line: 13, column: 1]]
用户.kt
@Entity
@Table(name = "user")
@Audited
@EntityListeners(AuditingEntityListener::class)
@Validated
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator::class, property = "id", scope = Int::class)
data class User(
@field:Id
@field:GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int,
@Valid
@Size(
min = 4,
message = "Username '\${validatedValue}' should be at least {min} characters long"
)
@NotEmpty(message = "asd")
var username: String = "",
...
@field:OneToOne(cascade = [CascadeType.ALL], optional = true)
var userInfo: UserInfo? = null
)
我正在发送用于反序列化的 JSON(在删除 @JsonIdentityInfo 时有效):
{
"username": "qwert",
"password": "tyui",
"email": "asdasd",
"phone": ""
}
注册方法:
@PostMapping("/users/signup")
fun addUser(@RequestBody @Valid user: User): JSendResponse<Unit> {
user.password = passwordEncoder.encode(user.password)
userService.save(user)
return JSendResponse(data = Unit)
}
统一更新:
这个问题的解决方案是在 Json 中显式设置 id 字段,因为它是在持久性级别上生成的。但我不想显式设置它,因为前端不知道新对象的id。
【问题讨论】:
-
您使用的是什么版本的 jackson-databind?
-
它是 2.9.9.3 和 jackson-core 2.9.9。实际上,我找到了解决方案,但我对此并不满意。更新了问题。
-
这似乎是某些版本的jackson-databind github.com/FasterXML/jackson-databind/issues/1367中的错误
-
现在我在存储库层之上使用 GraphQL,它几乎解决了我的所有问题。
标签: json spring-boot kotlin jackson deserialization