如何解决如何将json对象反序列化为展平格式直接字段?
我具有以下结构:
public class User {
private Account account;
//constuctors,getters and setters
}
public class Account {
private String id;
private String description;
//constructor,getters and setters
}
执行请求时,我需要创建以下JSON结构:
{
"account":
{
"id": "1","description": "Some description"
}
}
但是我想简短地指定此信息,并通过以下方式忽略(左为“ null”)“描述”字段:
{
"account": "1" // I want to set directly the id field in the account object.
}
我该怎么办?我尝试使用@JsonCreator
批注和@JsonUnwrapped
,但没有结果。
解决方法
您可以使用自定义解串器
public class AccountFromIdDeserializer extends StdDeserializer<Account> {
public AccountFromIdDeserializer() { this(null);}
protected AccountFromIdDeserializer(Class<Account> type) { super(type);}
@Override
public Account deserialize(JsonParser parser,DeserializationContext context)
throws IOException,JsonProcessingException {
Account account = new Account();
account.setId(parser.getValueAsString());
return account;
}
}
然后使用account
在User
的{{1}}节点上使用
@JsonDeserialize
,
最后,我使用了 @JsonCreator 批注并创建了两个构造函数:
@JsonCreator
public Account(@JsonProperty("id") String id,@JsonProperty("description") String description) {
this.id = id;
this.description = description;
}
@JsonCreator
public Account(String id) {
this.id = id;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。