0

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?

0

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.