简体   繁体   中英

Deserialize string to list class in c#

my json string data is

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

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

but should be 5 pieces.

what wrong? how to properly deserialize json string?

You need to deserialize an instance of RootObject .. since it is the root of the data. 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. In order to parse JSON directly into List, the JSON should be an array.

So, in your example above, if you modified your JSON string to be

[
  {"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. 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. 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  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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