gpt4 book ai didi

java - 改进了使用 Jackson 将嵌套 JSON 对象的 boolean 值转换为 Map 的方法

转载 作者:行者123 更新时间:2023-12-02 08:47:10 25 4
gpt4 key购买 nike

我有以下 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 类包含所有这些字段,我不想为所有 boolean 值设置单独的字段,而是拥有一个 Map< String, Boolean > 其中 String 是属性名称和 boolean 值是值。



@JsonProperty("failedDocuments")
private List<FailedDocumentsItem> failedDocuments;

@JsonProperty("eligible")
private boolean eligible;

@JsonProperty("donor")
private boolean donor;

最佳答案

添加 @JsonAnySetter字段(Jackson 2.8+)或方法:

Marker annotation that can be used to define a logical "any setter" mutator -- either using non-static two-argument method (first argument name of property, second value to set) or a field (of type Map or POJO) - to be used as a "fallback" handler for all otherwise unrecognized properties found from JSON content.

为简洁起见,使用公共(public)字段的示例。

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]]

关于java - 改进了使用 Jackson 将嵌套 JSON 对象的 boolean 值转换为 Map 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61004261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com