简体   繁体   中英

InvalidCastException while trying to deserialize JSON in C#

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

(old question but why not answer it :))

Your Json does not match a list of persons but is only 1 object containing a property persons (which is a list of persons)

Like:

public class AllPeople {
   public List<Person> Persons { get;set; }
}

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