读取并解析JSON数据

时间:2015-09-22 00:47:05

标签: c# json winforms

我是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。

2 个答案:

答案 0 :(得分:1)

使用命名空间System.Web.Script.Serialization;

像这样重写你的代码

JavaScriptSerializer js = new JavaScriptSerializer(); 
Location locs = js.Deserialize<Location>(ms);

答案 1 :(得分:1)

你的C#类是错误的。它应该有两个属性CityProvincejson对象是ListLocation。并尝试使用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);