Search code examples
c#json.net

Deserializing an unnamed array


I am having difficulty writing the appropriate annotations to represent data which is returned from a JSON Get request which returns data like so:

[
    {
        "ProductCode": "0129923083091",
        "Description": "DIESEL ",
        "SalesLitres": 6058.7347,
        "SalesValue": 6416.2000
    },
    {
        "ProductCode": "0134039344902",
        "Description": "UNLEADED ",
        "SalesLitres": 3489.8111,
        "SalesValue": 3695.7100
    },
    ...
]

(ellipsis above just indicating that I could have variable number of these items returned)

In my model class (I am using MVVM approach for a Xamarin project but that's not over relevant here) I am using annotations to represent the model attributes

 namespace App8.Models
    {

        public class ReportRow
        {
            [JsonProperty("ProductCode")]
            public string ProductCode { get; set; } = string.Empty;

            [JsonProperty("Description")]
            public string Description { get; set; } = string.Empty;

            [JsonProperty("SalesLitres")]
            public double SalesLitres { get; set; } = 0.0;

            [JsonProperty("SalesValue")]
            public double SalesValue { get; set; } = 0.0;    
        }
    }

I would like to annote another class which shows the container/contained relationship. However, I coming unstuck as there is no JSON attribute to provide in the annotation to represent the "root" of the returned collection.

I'd have no problem mapping the JSON to an object model for any JSON arrays which are named within the returned JSON. In that case I could create another class with a named JSON attribute which contained a C# List but I am trying to provide an appropriate model mapping for JSON which returns a list of items within an unnamed array.

Any ideas how I could approach this?


Solution

  • To deserialize that JSON, use:

    JsonConvert.DeserializeObject<List<ReportRow>>(json)
    

    (or any variant you wish, the key here is asking to deserialize a ICollection of ReportRow. It could be your own class implementing ICollection, or any of the builtins)

    The same idea follows to JsonTextReader or whatever other means of deserializing JSON.NET offers. Just use a ICollection<YourType> as target type.