我有问题反序列化REST Web服务提供的这个JSON。 这是我解决问题的建议
class Program
{
static void Main(string[] args)
{
RestResponse r = readFromWeb("http://www.808.dk/?code-csharp-httpwebrequest");
Console.ReadKey();
}
static RestResponse readFromWeb(string url)
{
HttpWebRequest request = HttpWebRequest.Create("http://services.groupkt.com/country/get/all") as HttpWebRequest;
request.ContentType = "application/json";
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream webStream = response.GetResponseStream();
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(RestResponse));
RestResponse resttresponse = (RestResponse)json.ReadObject(webStream);
return resttresponse;
}
}
DataContract类
[DataContract]
public class RestResponse
{
[DataMember]
public List<string> messages { get; set; }
[DataMember]
public List<City> result { get; set; }
}
[DataContract]
public class City
{
[DataMember]
public string name { get; set; }
[DataMember]
public string alpha2_code { get; set; }
[DataMember]
public string alpha3_code { get; set; }
}
有什么建议吗? 亲切。
答案 0 :(得分:0)
你仍然需要持有RestResponse的Json对象,看一下这个样本,它可以工作:
internal class Program
{
private static void Main(string[] args)
{
//var r = readFromWeb("http://www.808.dk/?code-csharp-httpwebrequest");
var r = readFromWeb("http://services.groupkt.com/country/get/all");
Trace.Write(r);
}
private static MyJson readFromWeb(string url)
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = "GET";
var response = request.GetResponse() as HttpWebResponse;
var webStream = response.GetResponseStream();
var json = new DataContractJsonSerializer(typeof (MyJson));
var resttresponse = (MyJson) json.ReadObject(webStream);
return resttresponse;
}
}
[DataContract]
public class MyJson
{
[DataMember(Name = "RestResponse")]
public RestResponse RestResponse { get; set; }
}
[DataContract]
public class RestResponse
{
[DataMember(Name = "messages")]
public string[] messages { get; set; }
[DataMember(Name = "result")]
public City[] result { get; set; }
}
[DataContract]
public class City
{
[DataMember(Name = "name")]
public string name { get; set; }
[DataMember(Name = "alpha2_code")]
public string alpha2_code { get; set; }
[DataMember(Name = "alpha3_code")]
public string alpha3_code { get; set; }
}