'.NET JsonDeserializer fails when I rename List<> property with JsonProperty
I'm trying to deserialize json that looks like this:
{
"Total": 1,
"Page": 1,
"Products": [
{
"ID": "524c20a3-a8ec-44f2-9685-311f1f7d1498",
"SKU": "Bread",
"Name": "Baked Bread",
"Category": "Other",
"Brand": null,
"Type": "Stock",
...
}
}
// shortened here. Full response comes from
https://dearinventory.docs.apiary.io/#reference/product/product/get
Everything works fine if I make my object list this:
public class PageProducts
{
public int Page { get; set; }
public int Total { get; set; }
public List<Product> Products { get; set; }
}
but, it will fail if I try to change the Products property to a different name like below:
public class PageProducts
{
public int Page { get; set; }
public int Total { get; set; }
[JsonProperty("Products")]
public List<Product> Items { get; set; }
}
What am I missing? I've done this lots of times for other properties. Is it something special with it being a List?
Thanks!
Solution 1:[1]
Please, provide more information on exception/inner exception details. because the problem not in serializing. as example I made a different conditions and all serialized correctly.
void Main()
{
string json = "{\"Total\":1,\"Page\":1,\"Products\":[{\"ID\":\"524c20a3-a8ec-44f2-9685-311f1f7d1498\",\"SKU\":\"Bread\",\"Name\":\"Baked Bread\",\"Category\":\"Other\",\"Brand\":null,\"Type\":\"Stock\"}]}";
Console.Write(JsonConvert.DeserializeObject<PageProducts>(json));
Console.Write(JsonConvert.DeserializeObject<PageProducts2>(json));
Console.Write(JsonConvert.DeserializeObject<PageProducts3>(json));
Console.Write(JsonConvert.DeserializeObject<PageProducts4>(json));
}
public class PageProducts
{
public int Page { get; set; }
public int Total { get; set; }
public List<Product> Products { get; set; }
}
public class PageProducts2
{
public int Page { get; set; }
public int Total { get; set; }
[JsonProperty("Products")]
public List<Product> Items { get; set; }
}
public class PageProducts3
{
public int Page { get; set; }
public int Total { get; set; }
public Product[] products { get; set; }
}
public class PageProducts4
{
public int Page { get; set; }
public int Total { get; set; }
[JsonProperty("Products")]
public Product[] items { get; set; }
}
public class Product{
public Guid ID {get;set;}
public string SKU {get;set;}
public string Name {get;set;}
public string Category {get;set;}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Power Mouse |