简体   繁体   English

在c#中反序列化字符串到列表类

[英]Deserialize string to list class in c#

my json string data is 我的json字符串数据是

string r= "{"data":
[
{"ForecastID":54239761,"StatusForecast":"Done"},
{"ForecastID":54240102,"StatusForecast":"Done"},
{"ForecastID":54240400,"StatusForecast":"Done"},
{"ForecastID":54240411,"StatusForecast":"Done"},
{"ForecastID":54240417,"StatusForecast":"Done"}
]
}"

and my json class is 我的json课程是

public class Datum
        {
            public string ForecastID { get; set; }
            public string StatusForecast { get; set; }
        }

        public class RootObject
        {
            public List<Datum> data { get; set; }
        }

i run this code 我运行此代码

JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Datum> ListAnswers = serializer.Deserialize<List<Datum>>(r);
Console.WriteLine("\n Deserialize: \n" + ListAnswers.Count  );

and have 0 count of ListAnswers.Count 并且有0个ListAnswers.Count计数

but should be 5 pieces. 但应该是5件。

what wrong? 怎么了? how to properly deserialize json string? 如何正确反序列化json字符串?

You need to deserialize an instance of RootObject .. since it is the root of the data. 您需要反序列化RootObject的实例..因为它是数据的根。 What you're trying to do right now is deserialize the whole thing as a list.. which it isn't. 你现在要做的是将整个事物反序列化为一个列表..它不是。 Its a root object with a list underneath it: 它是一个根对象,下面有一个列表:

RootObject obj = serializer.Deserialize<RootObject>(r);
foreach (var item in obj.data) {
    Console.WriteLine("\n Deserialize: \n" + item.ForecastID);
}

It looks like your JSON string is an object, not an array. 看起来你的JSON字符串是一个对象,而不是一个数组。 In order to parse JSON directly into List, the JSON should be an array. 为了将JSON直接解析为List,JSON应该是一个数组。

So, in your example above, if you modified your JSON string to be 因此,在上面的示例中,如果您修改了JSON字符串

[
  {"ForecastID":54239761,"StatusForecast":"Done"},
  {"ForecastID":54240102,"StatusForecast":"Done"},
  {"ForecastID":54240400,"StatusForecast":"Done"},
  {"ForecastID":54240411,"StatusForecast":"Done"},
  {"ForecastID":54240417,"StatusForecast":"Done"}
]

it would parse as you are expecting it to be. 它会解析你所期望的那样。

Another option would be to create a secondary C# class to reflect the structure of the JSON. 另一种选择是创建一个辅助C#类来反映JSON的结构。 Something along these lines: 这些方面的东西:

public class DataContainer
{
    public List<Datum> Data {get;set;}
}

This provides the 'data' property that is contained within your JSON string, so the serializer would populate the Data property with the list of Datum objects. 这提供了JSON字符串中包含的“data”属性,因此序列化程序将使用Datum对象列表填充Data属性。 Your calling code would then look like this: 您的调用代码将如下所示:

JavaScriptSerializer serializer = new JavaScriptSerializer();
DataContainer results = serializer.Deserialize<DataContainer>(r);
Console.WriteLine("\n Deserialize: \n" + results.Data.Count  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM