[英]How to deserialize json object into flatten format direct field?
我有以下结构:
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')'description'字段:
{
"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;
}
}
并使用@JsonDeserialize
在User
的account
节点上使用
public class User {
@JsonDeserialize(using = AccountFromIdDeserializer.class)
private Account account;
//constuctors, getters and setters
}
最后我使用了@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.