2015-05-05 38 views
0

我想反序列化一些JSON到列表使用JSON.NET;然而,有一個數字的方式:反序列化JSON與數字行

這裏是JSON:

"payment_info": { 
    "fb_id": "", 
    "order_items": { 
     "0": { 
     "product_id": "4534", 
     "type": "product", 
     "shipping_cost_per_item": "1.00", 
     "quantity": "3", 
     "price_each": "10.00", 
     "price_total": "30.00" 
     } 
    }, 

這裏是我的類:

public class OrderItem 
    { 
     public string product_id { get; set; } 
     public string type { get; set; } 
     public string shipping_cost_per_item { get; set; } 
     public string quantity { get; set; } 
     public string price_each { get; set; } 
     public string price_total { get; set; } 
    } 

    public class OrderItems 
    { 
     public List<OrderItem> Items { get; set; } 
    } 

我如何告訴轉換器忽略0?每個訂單項目將有1,2,3個。

回答

1

我在這裏看到一些問題。

首先,您的JSON無效;它似乎只是一個片段。有效的完整JSON將如下所示。 (我加了花括號,去掉後面的逗號和平衡的payment_info對象的括號內。)

{ 
    "payment_info": { 
     "fb_id": "", 
     "order_items": { 
      "0": { 
       "product_id": "4534", 
       "type": "product", 
       "shipping_cost_per_item": "1.00", 
       "quantity": "3", 
       "price_each": "10.00", 
       "price_total": "30.00" 
      } 
     } 
    } 
} 

由於您的片段被封閉在一個對象,你需要一個相應的頂級類反序列化到。該類需要一個payment_info屬性來保存現在你的OrderItems類。 (如果可能的話,我會建議將該類重命名爲PaymentInfo以避免混淆。)

二,OrderItems類中的Items屬性與JSON不匹配。在JSON中,它被命名爲order_items。由於它們不匹配,所以在反序列化時會得到一個空值。您需要重命名該屬性或使用[JsonProperty]屬性指定JSON屬性名稱。

三,您的JSON中的order_items屬性不是列表;它是一個對象。因此,如果嘗試將其反序列化到列表中(一旦修復了屬性名稱),就會出現錯誤。處理這種情況的通常解決方案是使用Dictionary<string, T>而不是List<T>

全部放在一起,如果你讓你的類是這樣的:

public class RootObject 
{ 
    public PaymentInfo payment_info { get; set; } 
} 

public class PaymentInfo 
{ 
    public Dictionary<string, OrderItem> order_items { get; set; } 
} 

public class OrderItem 
{ 
    public string product_id { get; set; } 
    public string type { get; set; } 
    public string shipping_cost_per_item { get; set; } 
    public string quantity { get; set; } 
    public string price_each { get; set; } 
    public string price_total { get; set; } 
} 

然後你就可以反序列化這樣的:

RootObject root = JsonConvert.DeserializeObject<RootObject>(json); 

foreach (OrderItem item in root.payment_info.order_items.Values) 
{ 
    Console.WriteLine("product id: " + item.product_id); 
    Console.WriteLine("type: " + item.type); 
    Console.WriteLine("shipping cost per item: " + item.shipping_cost_per_item); 
    Console.WriteLine("quantity: " + item.quantity); 
    Console.WriteLine("price per item: " + item.price_each); 
    Console.WriteLine("total price: " + item.price_total); 
} 

小提琴:https://dotnetfiddle.net/e0t8gX