Reputation: 8704
I can't figure out what's wrong with this:
public class Product
{
public string code { get; set; }
public string description { get; set; }
public string tp { get; set; }
}
public class Return
{
[JsonProperty("products")]
public List<Product> Products { get; set; }
}
public class BlingJson
{
[JsonProperty("return")]
public Return Return { get; set; }
}
public static void Run()
{
string str = "{ \"return\": { \"products\": [ { \"product\": { \"code\": \"8147-048PA\", \"description\": \"LEGEND 220v - HAIR CUTTER\", \"tp\": \"P\" } }, { \"product\": { \"code\": \"08164-148PA\", \"description\": \"FINALE - HAIR CUTTER\", \"tp\": \"P\" } } ] } }";
BlingJson json = JsonConvert.DeserializeObject<BlingJson>(str);
}
Upon deserialization, json.Return.Products
is a list containing two Products, but all properties (code
, description
and tp
) are null.
Formatted JSON for convenience:
{
"return": {
"products": [
{
"product": {
"code": "8147-048PA",
"description": "LEGEND 220v - HAIR CUTTER",
"tp": "P"
}
},
{
"product": {
"code": "08164-148PA",
"description": "FINALE - HAIR CUTTER",
"tp": "P"
}
}
]
}
}
I've seen similar questions but didn't find one that applies to this case. How to solve?
Thanks.
Upvotes: 3
Views: 417
Reputation: 509
You can either use a Wrapper class as mentioned by @DavidG to get it working per the given Json format. However, if you can't change your class, you have to tune your Json to this format:
{
"return": {
"products": [
{
"code": "A",
"description": "B",
"tp": "C"
},
{
"code": "D",
"description": "E",
"tp": "F"
}
]
}
}
Upvotes: 1
Reputation: 118937
Your JSON implies you need a wrapper around the product object. For example:
public class ProductWrapper
{
public Product Product { get; set; }
}
Which makes you Return
class look like this:
public class Return
{
[JsonProperty("products")]
public List<ProductWrapper> Products { get; set; }
}
Upvotes: 3