我是c#的新手,我试图从WSDL服务解析JSON数据。
以下是代码:
string cityjson = service.getcity();
/*
sample cityjson return
[{"City":"Alaminos","Province":"Pangasinan"},{"City":"Angeles","Province":"Pampanga"},{"City":"Antipolo","Province":"Rizal"}]
*/
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(cityjson)))
{
var serializer = new DataContractJsonSerializer(typeof(Location));
Location locs = (Location)serializer.ReadObject(ms);
Console.WriteLine(locs.Locations); // blank in console output.
}
这是我的datacontract代码
[DataContract]
public class Location
{
[DataMember]
public String[] Locations;
}
当我console.WriteLine(cityjson);
时,它打印整个json。
答案 0 :(得分:1)
使用命名空间System.Web.Script.Serialization;
像这样重写你的代码
JavaScriptSerializer js = new JavaScriptSerializer();
Location locs = js.Deserialize<Location>(ms);
答案 1 :(得分:1)
你的C#类是错误的。它应该有两个属性City
和Province
。json
对象是List
个Location
。并尝试使用JSON.Net
来解析您的json
数据。它重量轻且易于使用。您还可以使用可用资源将json
转换为C#类型。
public class Location
{
public String City { get; set; }
public String Province { get; set; }
}
var t = "[{'City':'Alaminos','Province':'Pangasinan'},{'City':'Angeles','Province':'Pampanga'},{'City':'Antipolo','Province':'Rizal'}]";
var type = JsonConvert.DeserializeObject<List<Location>>(t);