我有我試圖反序列化以下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)
,它使用傑克遜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: [email protected]; 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
的類型,並看到自動使用它的答案,要求我再次將類型名稱放在其他地方(例如@
屬性)。
我應該注意到,我習慣了Newtonsoft JSON.net,這個確切的例子完美地工作。我需要用多種語言編寫相同的庫,並且我希望代碼儘可能地與C#中的原始代碼儘可能接近,以便日後維護(儘管我認識到這並非總是可行)。 –
爲什麼不是你的'ComponentDependency'類'static'?爲什麼不是'所需'成員'List'(同樣適用於'Implements')?注意:對於實例成員名稱和方法,您應該使用小寫字母,將它們與類名混淆非常容易,否則 – fge
@fge我正在使用ProperCase(現在),因爲我試圖保持接口與現有的C#版本(其中標準是使用ProperCase),同時我研究了這些錯誤。一旦我準備好發佈它,我將解決這些問題。 –