How to Deserialize from web service JSON array or

2019-04-01 14:03发布

问题:

I created one web service application in windows phone 7. this is JSON array get from belowed uri. ...[{"id":4,"name":"Bangalore"},{"id":1,"name":"Chennai"},{"id":3,"name":"Hyderabad"},{"id":2,"name":"Mumbai"}]...

List item = (List)ds.ReadObject(msnew); In this line one bug(it says while run). There was an error deserializing the object of type.Data at the root level is invalid. Line 1, position 1.

coding:

public MainPage() { InitializeComponent(); }

    [DataContract]
    public class Item
    {           

        [DataMember]
        public int id
        {
            get;
            set;
        }

        [DataMember]
        public string name
        {
            get;
            set;
        }
    }
    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
        WebClient wc = new WebClient();
        wc.DownloadStringAsync(new Uri("http://75.101.161.83:8080/CityGuide/Cities?authId=CITY4@$pir*$y$t*m$13GUID*5"));
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
    }

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
       string MyJsonString = e.Result;
      // MessageBox.Show(e.Result);
       DataContractSerializer ds = new DataContractSerializer(typeof(Item));
       MemoryStream msnew = new MemoryStream(Encoding.UTF8.GetBytes(MyJsonString));
       List<Item> item = (List<Item>)ds.ReadObject(msnew);
    }

回答1:

There are 2 mistakes in what you're trying to do.

  1. You're using DataContractSerializer instead of DataContractJsonSerializer. The one you're trying to use is expecting XML, not JSON.

  2. You're trying to deserialize to a single Item and then convert that to a List<Item>, rather than an array, which is what json contains.

Try this instead:

  var ds = new DataContractJsonSerializer(typeof(Item[]));
  var msnew = new MemoryStream(Encoding.UTF8.GetBytes(MyJsonString));
  Item[] items = (Item[])ds.ReadObject(msnew);

If you later wanted to, you could convert the array to a list.



回答2:

You can add System.Json library from Silverlight SDK.
It isn't compiled for WP7, but for me it is working fine.