C#使用Newtonsoft.JSON反序列化List

时间:2018-02-23 15:51:01

标签: c# json deserialization

我目前正在尝试反序列化产品列表,并始终收到from defusedxml.minidom import parse以获取反序列化的结果。我已经审查了使用Newtonsoft.JSON序列化和反序列化集合的documentation,我仍然在努力找到发生这种情况的原因。在我目前的尝试中,我正在创建一个包装类null,用于保存我的产品列表。请参阅下面的简单JSON示例和模型类:

JSON示例

products

products.cs

{  
   "products":[  
      {  
         "title":"Some title",
         "id":123,
         "short_description":"some short description",
         "variations":[
            {  
               "id":234,
               "sku":"N123456789",
               "price":"1.50",
               "stock_quantity":2
            }
         ],
         "some_field_we_dont_care_about":987
      },
      {  
         "title":"A different title",
         "id":123,
         "short_description":"Some other short description",
         "variations":[
            {  
               "id":234,
               "sku":"NG1933410388C",
               "price":"2.00",
               "stock_quantity":800
            }
         ],
         "some_field_we_dont_care_about":123
      }
    ]
}

product.cs

  //wrapper class to facilitate json serialization
  public class products
  {
    List<product> productList { get; set; }
  }

和variation.cs

  public class product
  {
    public string title { get; set; }

    public int id { get; set; }

    public string short_description { get; set; }

    public List<variation> variations { get; set; }
  }

以及实际尝试反序列化JSON的代码:

  public class variation
  {
    public int id { get; set; }

    public int stock_quantity { get; set; }

    public string sku { get; set; }

    public decimal price { get; set; }
  }

1 个答案:

答案 0 :(得分:4)

这不是序列化的原因是因为您没有“产品”属性:

public class products
{
    List<product> productList { get; set; }
}

如您所见,您有一个“productList”属性。

最好的方法是将类结构更改为实际匹配JSON。你不必使用可怕的外壳,你可以使用适当的外壳,默认情况下它可以使用JSON.NET。还有一个名为[JsonProperty()]的JSON.NET属性。这允许您为C#对象提供所需的名称,但是规定了序列化/反序列化时json属性名称:

public class Variation
{
    public int Id { get; set; }

    [JsonProperty(PropertyName = "stock_quantity")]
    public int StockQuantity { get; set; }

    public string Sku { get; set; }

    public decimal Price { get; set; }
}

public class Product
{
    public string Title { get; set; }

    public int Id { get; set; }

    [JsonProperty(PropertyName = "short_description")]
    public string ShortDescription { get; set; }

    public List<Variation> Variations { get; set; }
}

public class ProductCollection
{
    List<Product> Products { get; set; }
}

然后稍微更改反序列化逻辑:

var productCollection = JsonConvert.DeserializeObject<ProductCollection>(productResponse.Content);