反序列化未命名的数组 [英] Deserializing an unnamed array

查看:99
本文介绍了反序列化未命名的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难编写适当的注释来表示从JSON Get请求返回的数据,该请求返回的数据如下:

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)

在我的模型类中(我正在为Xamarin项目使用MVVM方法,但是在这里并不过分相关),我正在使用注释来表示模型属性

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;    
        }
    }

我想说明另一个显示容器/包含关系的类.但是,由于注释中没有提供JSON属性来表示返回的集合的根",所以我感到很困惑.

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.

对于在返回的JSON中命名的任何JSON数组,将JSON映射到对象模型都没有问题.在那种情况下,我可以使用命名的JSON属性创建另一个类,该类包含一个C#列表,但是我试图为JSON提供适当的模型映射,该模型映射返回未命名数组中的项目列表.

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?

推荐答案

要反序列化JSON,请使用:

To deserialize that JSON, use:

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

(或您想要的任何变体,这里的关键是要求对ReportRowICollection进行反序列化.它可以是您自己的实现ICollection的类或任何内置函数)

(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)

JsonTextReader或任何其他反序列化JSON.NET提供的方法都遵循相同的想法.只需使用ICollection<YourType>作为目标类型.

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

这篇关于反序列化未命名的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆