杰克逊错误地将嵌套对象的值反序列化为父对象



我有以下JSON文件,我正在尝试对其进行反序列化:

{
    "name": "ComponentX",
    "implements": ["Temperature.Sensor"],
    "requires": [
        {"type": "interface", "name": "Temperature.Thermostat", "execute": [
            "../Thermostat.exe"
        ]}
    ]
}

它是对分布式系统的代码示例中的组件的描述。

这是应该反序列化到的类:

public class ComponentDescription {
    @JsonProperty("name")
    public String Name;
    @JsonProperty("implements")
    public String[] Implements;
    @JsonProperty("requires")
    public ComponentDependency[] Requires;
    @JsonIgnore
    public String RabbitConnectionName;
    private static final ObjectMapper mapper = new ObjectMapper();
    public static ComponentDescription FromJSON(String json)
        throws JsonParseException, JsonMappingException, IOException
    {
        return mapper.readValue(json, ComponentDescription.class);
    }
    public class ComponentDependency
    {
        @JsonCreator
        public ComponentDependency() {
            // Need an explicit default constructor in order to use Jackson.
        }
        @JsonProperty("type")
        public DependencyType Type;
        @JsonProperty("name")
        public String Name;
        /**
         * A list of ways to start the required component if it is not already running.
         */
        @JsonProperty("execute")
        public String[] Execute;
    }
    /**
     * A dependency can either be on "some implementation of an interface" or it
     * can be "a specific component", regardless of what other interface implementations
     * may be available.
     */
    public enum DependencyType
    {
        Interface,
        Component
    }
}

当我运行ComponentDescription.FromJSON(jsonData)时,它使用Jackson ObjectMapper将JSON反序列化为适当的类,我得到以下异常:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "type" (class edu.umd.cs.seam.dispatch.ComponentDescription), not marked as ignorable (3 known properties: , "implements", "name", "requires"])
 at [Source: java.io.StringReader@39346e64; line: 1, column: 103] (through reference chain: edu.umd.cs.seam.dispatch.ComponentDescription["requires"]->edu.umd.cs.seam.dispatch.ComponentDescription["type"])

Jackson似乎试图将JSON对象中的requires数组反序列化为ComponentDescription的数组,而不是ComponentDependency的数组如何使用正确的类我更喜欢一个能让Jackson查看public ComponentDependency[] Requires类型并自动使用它的答案,而不是一个需要我在其他地方重新输入类型名称的答案(例如@属性)。

我的猜测是问题来自于ComponentDependency不是static。由于它没有声明为static,这意味着它只能用ComponentDescription的现有实例进行实例化。

有关更多详细信息,请参阅此处。

最新更新