我具有以下结构:
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
,但没有结果。
答案 0 :(得分:4)
您可以使用自定义解串器
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
答案 1 :(得分:2)
最后,我使用了 @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;
}