views:

21

answers:

0

Hi everybody,

I'm trying to deserialize a Json stream. I'm working under Visual Studion for Windows Phone 7. Here is the code I'm using:

    public Accueil()
    {
        InitializeComponent();
        string baseUri = "http://path/to/my/webservice";
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(baseUri));
        request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
    }

    private void ReadCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
        {
            string returnedString= streamReader1.ReadToEnd();
            using (MemoryStream mStream = new MemoryStream(Encoding.Unicode.GetBytes(returnedString)))
            {
                List<Person> persons = new List<Person>();
                persons= returnResult(mStream);
            }


        }
    }

    private List<Person> returnResult(MemoryStream mStream)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Person>));
        return (List<Person>)serializer.ReadObject(mStream);
    }

As you can see, I call my webservice that gives me a response. Then, an async method is called to handle the webrequest and get the returned data. Finally, antoher method serilizes that data and returns a List of Person.

Of course, there is a "Person" class:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

The problem is that an invalid cast error is returned in the "returnResult" method:

InvalidCastException

At that line:

return (List<Person>)serializer.ReadObject(mStream);

Do you have an idea about the returned error? What Can I do?

Here is a Json sample:

{
  "Persons" : 
    [
      {"FirstName":"Foo","LastName":"Bar"},
      {"FirstName":"Hello","LastName":"World"}
    ]
}

Thank you,

Regards