Search code examples
c#jsondeserializationhttpresponsejavascriptserializer

Facing issue while deserializing the http resposne


I am using JavaScriptserializer to deserialize the HTTP response and convert back to object.

Code to retrieve the response:

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

    }

I am getting JSON string as below: 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",
    }
  ]
}

The issue happens I am able to get JSON response in the objText variable. But when i try to deserialize the reponse to NPIObj,the count is coming as 0.

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

myobj variable is having count as 0,even I am receiving the JSON response.

Here is my NPIObj class:

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

    }

Can anyone help me out how can i get the response to NPIObj?


Solution

  • You have a root property in your json: NPI. So you are not deserializing the array but the root object.

    Create another class:

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

    Then

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