How to Deserialize from web service JSON array or object?

爷,独闯天下 提交于 2019-12-05 02:25:49

问题


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.



来源:https://stackoverflow.com/questions/4439020/how-to-deserialize-from-web-service-json-array-or-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!