Deserializing an unnamed array

。_饼干妹妹 提交于 2019-12-10 14:10:29

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/39816903/deserializing-an-unnamed-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!