2013-06-23 23 views
0

我有我試圖反序列化以下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的類型,並看到自動使用它的答案,要求我再次將類型名稱放在其他地方(例如@屬性)。

+0

我應該注意到,我習慣了Newtonsoft JSON.net,這個確切的例子完美地工作。我需要用多種語言編寫相同的庫,並且我希望代碼儘可能地與C#中的原始代碼儘可能接近,以便日後維護(儘管我認識到這並非總是可行)。 –

+0

爲什麼不是你的'ComponentDependency'類'static'?爲什麼不是'所需'成員'List'(同樣適用於'Implements')?注意:對於實例成員名稱和方法,您應該使用小寫字母,將它們與類名混淆非常容易,否則 – fge

+0

@fge我正在使用ProperCase(現在),因爲我試圖保持接口與現有的C#版本(其中標準是使用ProperCase),同時我研究了這些錯誤。一旦我準備好發佈它,我將解決這些問題。 –

回答

3

我的猜測是問題來自ComponentDependency不是static。由於它沒有聲明爲static,這意味着它只能使用現有的ComponentDescription實例進行實例化。

有關更多詳細信息,請參閱here

+0

謝謝!你可以告訴我已經習慣了C#的方式在你鏈接的答案。 –