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

时间:2013-06-23 17:44:24

标签: java json jackson

我有以下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"])

杰克逊似乎试图将JSON对象中的requires数组反序列化为ComponentDescription的数组,而不是ComponentDependency的数组。 如何让它使用正确的课程?我希望得到杰克逊能够查看public ComponentDependency[] Requires类型的答案,并自动将其用于需要我放置的答案再次在其他地方输入类型名称(例如@属性)。

1 个答案:

答案 0 :(得分:3)

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

有关详细信息,请参阅here