使用 [JsonProperty] 将 Json 参数与类型为 List 的 C# 类属性匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13287086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:04:48  来源:igfitidea点击:

Using [JsonProperty] to match Json parameters to C# class properties which are type List

c#jsonjson.net

提问by Bataleon

I'm trying to deserialize the following Json response (using Json.NET):

我正在尝试反序列化以下 Json 响应(使用 Json.NET):

[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Yes", "1":"No"} … ]

Into objects of this type:

进入这种类型的对象:

    class Poll
    {
        [JsonProperty("pollid")]
        public int pollid { get; set; }
        [JsonProperty("question")]
        public string question { get; set; }
        [JsonProperty("start")]
        public DateTime start { get; set; }
        [JsonProperty("end")]
        public DateTime end { get; set; }
        [JsonProperty("category")]
        public string category { get; set; }

        // PROBLEM AREA
        [JsonProperty("0")] // Json parameter names are 0 to 9. How can I 'match' these to the List elements?
        public List<string> polloptions { get; set; }
    }

How would I use the [JsonProperty]attribute when creating a List? (Assuming the Json parameter names to be contained in this List are "0" to "9"). I've spent the last few hours trying different methods without any luck.

[JsonProperty]创建列表时如何使用该属性?(假设要包含在此列表中的 Json 参数名称为“0”到“9”)。在过去的几个小时里,我一直在尝试不同的方法,但没有任何运气。

Many thanks

非常感谢

采纳答案by nick_w

One option would be to do something like this (I took the [JsonProperty("0")]off polloptionsfirst):

一种选择是做这样的事情(我先[JsonProperty("0")]脱掉了polloptions):

int option;
Poll poll = JsonConvert.DeserializeObject<Poll>(json);
JContainer container = (JContainer)JsonConvert.DeserializeObject(json);

poll.polloptions = container.Where(t => t as JProperty != null)
    .Cast<JProperty>().Where(p => int.TryParse(p.Name, out option))
    .Select(p => p.Value.Value<string>()).ToList();

The first step is to deserialize as per normal - this will take care of every property except for polloptions. The next step is to deserialize to a JContainerso that we can get at the individual tokens and create a list out of the ones with numeric names (hence the int.TryParse(p.Name, out option)).

第一步是按正常方式反序列化 - 这将处理除polloptions. 下一步是反序列化为 a ,JContainer以便我们可以获取单个标记并从具有数字名称的标记(因此是int.TryParse(p.Name, out option))中创建一个列表。

What this will give you as a list populated with the yes/no values. If you would also like the names of the poll options as well as the values, consider this:

这将为您提供什么,作为填充是/否值的列表。如果您还想要轮询选项的名称以及值,请考虑:

Change the polloptionsproperty to:

polloptions属性更改为:

public List<PollOption> polloptions { get; set; }

Where PollOptionis:

在哪里PollOption

class PollOption
{
    public int Name { get; set; }
    public string Value { get; set; }
}

When deserializing:

反序列化时:

Poll poll = JsonConvert.DeserializeObject<Poll>(json);
JContainer container = (JContainer)JsonConvert.DeserializeObject(json);

var pollOptionNames = container.Where(t => t as JProperty != null)
    .Cast<JProperty>().Where(p => int.TryParse(p.Name, out option))
    .Select(p => int.Parse(p.Name)).ToList();

var pollOptionValues = container.Where(t => t as JProperty != null)
    .Cast<JProperty>().Where(p => int.TryParse(p.Name, out option))
    .Select(p => p.Value.Value<string>()).ToList();

poll.polloptions = pollOptionNames.Select((n, i) =>
    new PollOption() { Name = n, Value = pollOptionValues[i] }).ToList();