DataContractJsonSerializer ReadObject return NULL 值?

DataContractJsonSerializer ReadObject return NULL value?

我在反序列化由 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 class

[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; }
}

有什么建议吗? 亲切

您仍然需要 Json 包含 RestResponse 的对象,看看这个示例,它有效:

  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; }
  }