locked
How to deserialize data at client side when web api action return data in xml format RRS feed

  • Question

  • User264732274 posted

    1) first situation is say my web api action return data in xml format. so tell me when i will call that web api action with httpclient then how could i deserialize that customer xml data to my customer class at client side ?

    suppose this is my web api actions

       [RoutePrefix("api/customer")]
        public class CustomerController : ApiController
        {
            static readonly ICustomerRepository repository = new CustomerRepository();
    
            [HttpGet, Route("GetAll")]
            public HttpResponseMessage GetAllCustomers()
            {
                //return new Response(true, "SUCCESS", repository.GetAll());
                return Request.CreateResponse(HttpStatusCode.OK, new Response(true, "SUCCESS", repository.GetAll()));
            }
    
            [HttpGet, Route("GetByID/{customerID}")]
            public Response GetCustomer(string customerID)
            {
                Customer customer = repository.Get(customerID);
                if (customer == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                return new Response(true, "SUCCESS", customer);
                //return Request.CreateResponse(HttpStatusCode.OK, response);
            }
    
            [HttpGet, Route("GetByCountryName/{country}")]
            public IEnumerable<Customer> GetCustomersByCountry(string country)
            {
                return repository.GetAll().Where(
                    c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
            }
    
            public HttpResponseMessage PostCustomer(Customer customer)
            {
                customer = repository.Add(customer);
                var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
    
                string uri = Url.Link("DefaultApi", new { customerID = customer.CustomerID });
                response.Headers.Location = new Uri(uri);
                return response;
            }
    
            public void PutProduct(string customerID, Customer customer)
            {
                customer.CustomerID = customerID;
                if (!repository.Update(customer))
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
            }
    
            public void DeleteProduct(string customerID)
            {
                Customer customer = repository.Get(customerID);
                if (customer == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                repository.Remove(customerID);
            }
        }
    public class Response
        {
            bool IsSuccess = false;
            string Message;
            object ResponseData;
    
            public Response(bool status, string message, object data)
            {
                IsSuccess = status;
                Message = message;
                ResponseData = data;
            }
        }
       public class Customer
        {
            public string CustomerID { get; set; }
            public string CompanyName { get; set; }
            public string ContactName { get; set; }
            public string ContactTitle { get; set; }
    
            public string Address { get; set; }
    
            public string Region { get; set; }
    
            public string PostalCode { get; set; }
            public string City { get; set; }
            public string Country { get; set; }
            public string Phone { get; set; }
            public string Fax { get; set; }
        }

    now calling like this way

                var baseAddress = "http://localhost:8010/api/customer/GetAll";
                using (var client = new HttpClient())
                {
                    using (var response = await client.GetAsync(baseAddress))
                    {
                        if (response.IsSuccessStatusCode)
                        {
    
    
                        }
                        else
                        {
                            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                        }
                    }
                } 

    when response.IsSuccessStatusCode is true then tell me how could i read the response and extract the customer data from response class.

    just give me sample code of HttpClient which show me how to deserialize response and customer class. please include sample code which i can use. thanks

    Friday, August 26, 2016 9:43 AM

Answers

  • User36583972 posted

    Hi sudip_inn,

    You can try the following code:

    when response.IsSuccessStatusCode is true then tell me how could i read the response

        using (var client = new System.Net.Http.HttpClient())
                {
                    // HTTP POST
                    var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
                    client.BaseAddress = new Uri(baseUrl);
                  
                    var response = client.GetAsync("/api/Customer/GetAll").Result;
                    string res = "";
                    using (HttpContent content = response.Content)
                    {
                        // ... Read the string.
                        Task<string> result = content.ReadAsStringAsync();
                        res = result.Result;
                    }
              }

    extract the customer data from response class

           //res string
                    XDocument doc = XDocument.Parse(res);
                    var Customerresult = (from ele in doc.Descendants("ResponseData")
                                          select new Customer
                                          {
                                              ID = (string)ele.Element("ID"),
                                              name = (string)ele.Element("name")
                                          }).ToList();
                    foreach (Customer t in Customerresult)
                    {
                        HttpContext.Current.Response.Write(t.name);
                    }

    XML Serialization and Deserialization in C#:

    https://blog.udemy.com/csharp-serialize-to-xml/

    Serializing and Deserializing XML String:

    http://www.c-sharpcorner.com/article/serializing-and-deserializing-xml-string/

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, August 28, 2016 10:55 AM
  • User264732274 posted

    Another best way to achieve it below way

    var baseAddress = "http://localhost:8010/api/customer/GetAll";
    using (var client = new HttpClient())
    {
        using (var response = await client.GetAsync(baseAddress))
        {
            if (response.IsSuccessStatusCode)
            {
                  using (HttpContent content = response.Content)
                  {
                      string result = await content.ReadAsStringAsync();
                      var newCustomer = (customer)serializer.Deserialize(result);
                  }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }
    } 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 29, 2016 8:55 AM

All replies

  • User-1404113929 posted

    hi,

    use bellow code.

    if (response.IsSuccessStatusCode)
                        {
      WebResponse webResponse = request.GetResponse();
                var responseText = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
    
                        }

    thanks,

    murali

    Friday, August 26, 2016 10:09 AM
  • User264732274 posted

    this is just non-sense sample code or taken from any web site without understanding the question.

    where it is shown in code that incoming response is getting deserialize to customer class or any other class in your code ?

    Friday, August 26, 2016 11:37 AM
  • User-1404113929 posted

    Hi,<br>
    It is not taken from any other website , it was taken from my dev environment . nd this is forum site , every body should try to post solutions,it was my mistake I understand wrongly if it is work for you , you just marked as answer nd you don't have right to blame
    others.
    Friday, August 26, 2016 4:25 PM
  • User475983607 posted

    XML serialization in .NET has been around a long long time and it is extremely easy to do if you read the openly published documentation.  Essentially, fire up the XmlSerializer object by passing the the type you want deserialized.  Then pass the Deserialize() method an XML stream.  that's it... read the following MSDN reference docs and you should be good to go.  If you need help, post your source code with a description of the problem.

    https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx

    https://msdn.microsoft.com/en-us/library/fa420a9y(v=vs.110).aspx

    https://www.google.com/?ion=1&espv=2#q=XmlSerializer

    Friday, August 26, 2016 7:51 PM
  • User36583972 posted

    Hi sudip_inn,

    You can try the following code:

    when response.IsSuccessStatusCode is true then tell me how could i read the response

        using (var client = new System.Net.Http.HttpClient())
                {
                    // HTTP POST
                    var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
                    client.BaseAddress = new Uri(baseUrl);
                  
                    var response = client.GetAsync("/api/Customer/GetAll").Result;
                    string res = "";
                    using (HttpContent content = response.Content)
                    {
                        // ... Read the string.
                        Task<string> result = content.ReadAsStringAsync();
                        res = result.Result;
                    }
              }

    extract the customer data from response class

           //res string
                    XDocument doc = XDocument.Parse(res);
                    var Customerresult = (from ele in doc.Descendants("ResponseData")
                                          select new Customer
                                          {
                                              ID = (string)ele.Element("ID"),
                                              name = (string)ele.Element("name")
                                          }).ToList();
                    foreach (Customer t in Customerresult)
                    {
                        HttpContext.Current.Response.Write(t.name);
                    }

    XML Serialization and Deserialization in C#:

    https://blog.udemy.com/csharp-serialize-to-xml/

    Serializing and Deserializing XML String:

    http://www.c-sharpcorner.com/article/serializing-and-deserializing-xml-string/

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, August 28, 2016 10:55 AM
  • User264732274 posted

    Another best way to achieve it below way

    var baseAddress = "http://localhost:8010/api/customer/GetAll";
    using (var client = new HttpClient())
    {
        using (var response = await client.GetAsync(baseAddress))
        {
            if (response.IsSuccessStatusCode)
            {
                  using (HttpContent content = response.Content)
                  {
                      string result = await content.ReadAsStringAsync();
                      var newCustomer = (customer)serializer.Deserialize(result);
                  }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }
    } 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 29, 2016 8:55 AM