2014-01-21 137 views
0

我正在使用JSON.NET反序列化,但將對象實例化並將其所有屬性設置爲null。如何使用JSON.NET&c#反序列化JSON而不使用null屬性

JSON

{ 
    "verify-purchase": 
    { 
     "item_name":"Pipeline.NET Task Scheduler", 
     "item_id":"1111111", 
     "created_at":"Wed Jun 12 15:56:02 +1000 2013", 
     "buyer":"xxxxxxxx", 
     "licence":"Regular License" 
    } 
} 

C#類

public class VerifyPurchase 
{ 
    [JsonProperty("item_name")] 
    public string ItemName { get; set; } 

    [JsonProperty("item_id")] 
    public string ItemId { get; set; } 

    [JsonProperty("created_at")] 
    public string CreatedAt { get; set; } 

    [JsonProperty("buyer")] 
    public string Buyer { get; set; } 

    [JsonProperty("licence")] 
    public string Licence { get; set; } 
} 

C#反序列化

var purchase = JsonConvert.DeserializeObject<VerifyPurchase>(jsonText); 

這看起來很簡單。這裏有什麼問題導致NULL屬性?

回答

1

你可以有一個包裝類,允許您指定verify-purchase屬性:

public class Wrapper 
{ 
    [JsonProperty("verify-purchase")] 
    public VerifyPurchase Purchase { get; set; } 
} 

,你會反序列化:

var wrapper = JsonConvert.DeserializeObject<Wrapper>(jsonText); 
VerifyPurchase purchase = wrapper.Purchase; 
// the purchase.* properties should be assigned at this stage 
+0

我嘗試過的包裝,但不包括該屬性。感謝您的解決方案。 – avantprime