Search code examples
c#jsonjson-deserialization

Deserialize Json with top Array and first unnamed object


I am consuming an API that returns the following JSON:

[
    {
        "product": {
            "id": 2,
            "name": "Auto"
        }
    }
]

So, I am trying to deserialize this in C# object wihout success.

I'd tried a lot of other's stackoverflow solutions.

Here are my attempt:

public class DomainMessageResponse : BaseResponseMessage
{
    public Example data { get; set; }
}

public class Example
{
    [JsonProperty("product")]
    public Product product { get; set; }
}

public class Product
{
    [JsonProperty("id")]
    public int id { get; set; }

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

The problem is that the JSON is beginning with [] and our generic method (that I use from an internal framework) was not able to due with it. I'm getting the following exception:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type....

Thanks @EZI and @eocron for valid solution's.


Solution

  • You should deserialize to array/list. Below code should work...

    var list = JsonConvert.DeserializeObject<List<Item>>(json);
    
    public class Product
    {
        public int id { get; set; }
        public string name { get; set; }
    }
    
    public class Item
    {
        public Product product { get; set; }
    }