1

The subject sounds unclear, but the logic is very simple. I have a returned response data that is in json format. I want to Deserialize it into .net object which I defined already. I use JavaScriptSerializer class Deserialize method, it requires the parameter to be string. Now my response data is in json format, and has more than one roots.

My code is

 WebRequest request = WebRequest.Create  ("https://xxx.xxxxxx.com/xxxxx");
    request.Method = "GET";
    request.ContentType = "application/json";
    var response = (HttpWebResponse)request.GetResponse();
    using (var streamReader = new StreamReader(response.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
    }

The responseText value is

[
 {
 "webinarKey":5303085652037254656,
 "subject":"Test+Webinar+One",
 "description":"Test+Webinar+One+Description",
 "organizerKey":73563532324,
 "times":[{"startTime":"2011-04-26T17:00:00Z","endTime":"2011-04-26T18:00:00Z"}]
 },
 {
 "webinarKey":9068582024170238208,
 "name":"Test+Webinar+Two",
 "description":"Test Webinar Two Description",
 "organizerKey":73563532324,
 "times":[{"startTime":"2011-04-26T17:00:00Z","endTime":"2011-04-26T18:00:00Z"}]
 }
 ]

I use following code to deserialize responseText to a .net object that I defined.

JavaScriptSerializer ser = new JavaScriptSerializer();
Webinar w=ser.Deserialize<Webinar>(responseText);

Error comes out says responseText is an array, not string. Then how to split responseText? I don't think it is appropriate to use string.split() method here.

Steven Zack
  • 4,984
  • 19
  • 57
  • 88
  • 1
    Have you tried to deserialize array not single object `Webinar[]`? `ser.Deserialize(responseText);` – Samich Feb 08 '12 at 17:03

2 Answers2

1

Your response text is indeed a json array (containing 2 elements), as indicated by the [ and ] characters. Try the following:

Webinar[] w=ser.Deserialize<Webinar[]>(responseText);
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
0

Have you tried: List<Webinar> w=ser.Deserialize<List<Webinar>>(responseText);?

Vinicius Ottoni
  • 4,631
  • 9
  • 42
  • 64