java - 使用 Jackson 将嵌套 JSON 对象的布尔值转换为 Map 的改进方法
问题描述
我有以下 JSON 对象
{
"donor": "Y",
"bloodType": null,
"eligibility": {
"categoryEligible": false,
"suspensionEligible": false,
"paidFinesEligible": false,
"pointSystemEligible": false,
"failedDocuments": [
{
"type": "SOMETHING",
"reason": "SOMETHING_ELSE"
}
],
"eligible": false,
}
}
我正在使用 Jackson 将其转换为我的域对象。以下是我正在使用的字段:
private String donor;
@JsonProperty("eligibility")
private Eligibility eligibility;
Eligibility 类包含所有这些字段,我不想让所有布尔值都有单独的字段,而是有一个 Map < String, Boolean >,其中 String 是属性名称,布尔值是值。
@JsonProperty("failedDocuments")
private List<FailedDocumentsItem> failedDocuments;
@JsonProperty("eligible")
private boolean eligible;
@JsonProperty("donor")
private boolean donor;
解决方案
添加一个@JsonAnySetter
字段(Jackson 2.8+)或方法:
可用于定义逻辑“任何 setter”mutator 的标记注释 - 使用非静态双参数方法(属性的第一个参数名称,要设置的第二个值)或字段(类型
Map
或 POJO)用作从 JSON 内容中找到的所有其他无法识别的属性的“后备”处理程序。
为简洁起见,使用公共字段的示例。
public class Test {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
Root root = mapper.readValue(new File("test.json"), Root.class);
System.out.println("donor = " + root.donor);
System.out.println("flags = " + root.eligibility.flags);
System.out.println("failedDocuments = " + root.eligibility.failedDocuments);
}
}
class Root {
public Boolean realId;
public String donor;
public Boolean bloodType;
public Boolean selectiveServiceCandidate;
public Eligibility eligibility;
}
class Eligibility {
@JsonAnySetter
public Map<String, Boolean> flags = new HashMap<>();
public List<FailedDocument> failedDocuments;
}
class FailedDocument {
public String type;
public String reason;
@Override
public String toString() {
return "FailedDocument[type=" + this.type + ", reason=" + this.reason + "]";
}
}
输出
donor = Y
flags = {paidFinesEligible=false, hasRealId=false, suspensionEligible=false, acaaEligible=false, eligibleIgnoreRenewalDate=false, eligibleDocuments=false, cardStatusEligible=false, expirationDateEligible=false, eligible=false, citizenEligible=false, pointSystemEligible=false, ageEligible=false, gravamenesEligible=false, categoryEligible=false, eligibleMedical=false}
failedDocuments = [FailedDocument[type=CERTIFICATE_CITIZENSHIP, reason=MISSING]]
推荐阅读
- vba - VBA Excel,更改单元格内一个单词的格式
- python - 根据另一列的差异更改列值
- unix - 参数不匹配:颠覆
- c# - 如何分隔 C# 元组值以匹配方法参数
- javascript - 为什么在重新渲染父级时,一组记忆的前向引用组件会重新运行代码?
- rocket.chat - RocketApp在MacOS上的配置位置
- airflow - StatsD 显示“go_gc_duration”指标,但不显示气流指标
- python - 每次打开页面时,使用多个 Plotly 绘图确保 Jupyter 的相同页面呈现?
- c# - 找不到 StackOverflow 异常
- angular - Angular - 如何将组件传递/组合成通用组件?