如何将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;
  }
}

然后使用accountUser的{​​{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;
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...