I am trying to deserialize a Json stream. I work in Visual Studio for Windows Phone 7. Here is the code I use:
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 am calling my web service, which gives me an answer. The async method is then called to process the web request and retrieve the returned data. Finally, the antoher method serializes this 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 casting error is returned in the returnResult method:
InvalidCastException
In this line:
return (List<Person>)serializer.ReadObject(mStream);
Do you have an idea about the returned error? What can I do?
Here is a Json example:
{
"Persons" :
[
{"FirstName":"Foo","LastName":"Bar"},
{"FirstName":"Hello","LastName":"World"}
]
}
Thank,
Hi
source
share