我有以下我试图反序列化的 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"])
似乎杰克逊试图将requires
JSON 对象中的数组反序列化为数组ComponentDescription
而不是ComponentDependency
. 如何让它使用正确的类?我更喜欢让杰克逊查看类型public ComponentDependency[] Requires
并自动使用它的答案,而不是要求我再次将类型名称放入其他地方(例如@
属性)的答案。