问题
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).

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.
You're using
DataContractSerializer
instead ofDataContractJsonSerializer
. The one you're trying to use is expecting XML, not JSON.You're trying to deserialize to a single
Item
and then convert that to aList<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