如何使用 Jackson 将 JSON 字符串序列化为 JAVA 对象

How to Serialise a JSON String to a JAVA Object using Jackson

我在将下面的 JSON 字符串反序列化为 Java 对象时遇到问题。

{
    "action": {
               "onWarning":{
                   "alert":{
                          "isEnabled": true,
                          "name": ""
                           }
                   },
               "onError":{
                 "alert":{
                        "isEnabled": true,
                        "name": ""
                        }
                   },
                "onSuccess":{
                 "alert":{
                        "isEnabled": true,
                        "name": ""
                        }
                   }
             }
}

下面的代码应该可以工作,但我认为我的问题是我传递给它的映射器 -

ObjectMapper mapper = new ObjectMapper();
JobConfig lib = mapper.readValue(jsonString, JobConfig.class);
System.out.println(lib.action.onWarning.alert.isEnabled);

我传递给它的映射器如下所示:

Alert.java

public class Alert{
    @JsonProperty("isEnabled")
    public boolean isEnabled;

    @JsonProperty("name")
    public String name;
}

AlertConfig.java

public class AlertConfig {
    
    @JsonProperty("onSuccess")
    public Alert onSuccess;

    @JsonProperty("onWarning")
    public Alert onWarning;

    @JsonProperty("onError")
    public Alert onError;
}

JobConfig.java

public class JobConfig {
    @JsonProperty("action")
    public AlertConfig action;
}

我得到的错误是:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "alert" (class com.test.dv.service.domain.Alert), not marked as ignorable (2 known properties: "name", "isEnabled"])

我也不知道如何将警报 JSON 的内容命名为警报,但它已经被命名为警报。

错误是正确的,在你的 DTO 中你的 onError/Success/Warning 字段是类型 Alert,类型警报有 nameisEnabled,你没有alert 字段如 json

"onError":{
    "alert":{

您缺少具有 属性 alertonError/Success/Warning 应该属于该类型的 DTO (或从 json 中删除 alert 属性)

您应该像下面这样创建一个 AlertWrapper Class -

public class AlertWrapper {

    @JsonProperty("alert")
    public Alert alert;
}

并且您的 AlertConfig class 应该包含如下所示的 AlertWrapper -

public class AlertConfig {

    @JsonProperty("onSuccess")
    public AlertWrapper onSuccess;

    @JsonProperty("onWarning")
    public AlertWrapper onWarning;

    @JsonProperty("onError")
    public AlertWrapper onError;
}

这样做你将完成你的 DTO