在反序列化http resposne时遇到问题

时间:2016-02-25 10:25:13

标签: c# json deserialization httpresponse javascriptserializer

我使用JavaScriptserializer来反序列化HTTP响应并转换回对象。

检索响应的代码:

 using (var response = (HttpWebResponse)request.GetResponse())
  {
    var responseValue = string.Empty;

    if (response.StatusCode != HttpStatusCode.OK)
    {
      var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
      throw new ApplicationException(message);
    }

    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        var objText = reader.ReadToEnd();

        var myobj = js.Deserialize<List<NPIObj>>(objText);

    }

我收到JSON字符串如下: objText:

{
  "NPI": [
    {
      "NPI": "1003000118",
      "EntityType": "Organization",
      "IsOrgSubpart": "N",
      "OrgName": "STEVEN ENGEL PEDIATRICS",
      "FirstLineMailingAddress": "1700 NEUSE BLVD",
      "MailingAddressCityName": "NEW BERN",
      "MailingAddressStateName": "NC",
      "MailingAddressPostalCode": "28560-2304",
      "MailingAddressCountryCode": "US",
      "MailingAddressTelephoneNumber": "252-637-3799",
      "MailingAddressFaxNumber": "252-633-0944",
      "FirstLinePracticeLocationAddress": "1700 NEUSE BLVD",
      "PracticeLocationAddressCityName": "NEW BERN",
      "PracticeLocationAddressStateName": "NC",
    }
  ]
}

问题发生我能够在objText变量中获得JSON响应。 但是当我尝试将响应反序列化为NPIObj时,计数将变为0。

 var myobj = js.Deserialize<List<NPIObj>>(objText);

myobj变量的计数为0,即使我收到JSON响应。

这是我的NPIObj课程:

public class NPIObj
    {
        public string EntityType { get; set; }
        public string FirstLineMailingAddress { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MailingAddressCityName { get; set; }
        public string MailingAddressCountryCode { get; set; }
        public string MailingAddressPostalCode { get; set; }
        public string MailingAddressStateName { get; set; }
        public string MiddleName { get; set; }
        public string NamePrefix { get; set; }
        public string NPI { get; set; }
        public string OrgName { get; set; }
        public string SecondLineMailingAddress { get; set; }

    }

任何人都可以帮助我如何获得对NPIObj的回复?

1 个答案:

答案 0 :(得分:1)

你的json中有一个root属性:NPI。所以你不是反序列化数组而是根对象。

创建另一个类:

public class NPIRoot 
{
  public List<NPIObj> NPI { get; set; }
}

然后

var myobj = js.Deserialize<NPIRoot>(objText);