英文:
How to deserialize json object into flatten format direct field?
问题
Here is the translated code portion:
{
"account": "1" // 我想直接设置账户对象中的id字段。
}
If you have any more code or text that needs translation, please feel free to provide it.
英文:
I have the following structure:
public class User {
private Account account;
//constuctors, getters and setters
}
public class Account {
private String id;
private String description;
//constructor, getters and setters
}
When I performing the request I need to create the following JSON structure:
{
"account":
{
"id": "1",
"description": "Some description"
}
}
But I want to specify this information in a short way and ignore(left 'null') the 'description' field in the following way:
{
"account": "1" // I want to set directly the id field in the account object.
}
How may I do it? I tried @JsonCreator
annotation and @JsonUnwrapped
but without result.
答案1
得分: 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;
}
}
然后在 User
的 account
节点上使用 @JsonDeserialize
public class User {
@JsonDeserialize(using = AccountFromIdDeserializer.class)
private Account account;
//构造函数、getter 和 setter
}
英文:
You can use a custom deserializer
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;
}
}
And use on account
node of User
using @JsonDeserialize
public class User {
@JsonDeserialize(using = AccountFromIdDeserializer.class)
private Account account;
//constuctors, getters and setters
}
答案2
得分: 2
Sure, here is the translated code part without any additional content:
最后,我使用了 @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;
}
英文:
Finally I used @JsonCreator annotation and created two constructors:
@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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论