2010-06-04 118 views
6

我想用JSON.NET反序列化填充數據的C#對象(ImportedProductCodesContainer)。在C#中的JSON.NET反序列化導致空對象

ImportedProductCodesContainer.cs:

using Newtonsoft.Json; 

[JsonObject(MemberSerialization.OptOut)] 
public class ImportedProductCodesContainer 
{ 
    public ImportedProductCodesContainer() 
    { 

    } 

    [JsonProperty] 
    public ActionType Action { get; set; } 

    [JsonProperty] 
    public string ProductListRaw { get; set; } 


    public enum ActionType {Append=1, Replace}; 
} 

JSON字符串:

{"ImportedProductCodesContainer":{"ProductListRaw":"1 23","Action":"Append"}} 

C#代碼:

var serializer = new JsonSerializer(); 
var importedProductCodesContainer = 
    JsonConvert.DeserializeObject<ImportedProductCodesContainer>(argument); 

的問題是,importedProductCodesContainer保持運行上面的代碼後空( Action = 0,ProductListRaw =空值)。你能幫我弄清楚有什麼問題嗎?

回答

1

你有一個太多的ImportedProductCodesContainer的水平。它會創建一個新的ImportedProductCodesContainer對象(來自模板化解串器),然後試圖在其上設置一個名爲ImportedProductCodesContainer(來自JSON頂層)的屬性,該屬性將是包含其他兩個值的結構。如果反序列化內部唯一

{"ProductListRaw":"1 23","Action":"Append"} 

那麼你應該得到你期待的對象,也可以創建一個新的結構與ImportedProductCodesContainer財產

[JsonObject(MemberSerialization.OptOut)] 
public class ImportedProductCodesContainerWrapper 
{ 
    [JsonProperty] 
    public ImportedProductCodesContainer ImportedProductCodesContainer { get; set; } 
} 

,並與模板,然後你解串器你原來的JSON應該可以工作。

也可以使用該JSON庫中的其他屬性/標誌更改此行爲,但我不太清楚。

+0

謝謝,這工作! – 2010-06-04 09:20:45