How to popular an object with the return of a Webapi query?

Asked

Viewed 429 times

2

How popular the variable _clientes guy Cliente with the return of a consultation to a WebApi?

Following the great suggestion of Damon Dudek I came across the error below:

inserir a descrição da imagem aqui

    public class ClienteController : Controller
        {
            HttpClient _client;
            Uri _clienteUri;

            // GET: Cliente
            public ActionResult Index()
            {
                if (_client == null)
                {
                    _client = new HttpClient();
                    _client.BaseAddress = new Uri("http://localhost:58573");
                    _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                }
                ArrayOfCliente _clientes = Listar();
                return View(_clientes);
            }

        private ArrayOfCliente Listar()
        { 
            HttpResponseMessage response = _client.GetAsync("api/clientes").Result;
            ArrayOfCliente oPessoa = new ArrayOfCliente();

            if (response.IsSuccessStatusCode)
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ArrayOfCliente));

//
                using (TextReader reader = new StringReader(response))
                {
                    ArrayOfCliente result = (ArrayOfCliente)serializer.Deserialize(reader);
                }
            }
            else
            {
                Response.Write(response.StatusCode.ToString() + " - " + response.ReasonPhrase);
            }
            return oPessoa;
        }

Return of the Webapi:

<ArrayOfCliente xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Dominio.Apolo.Modelo">
<Cliente>
<ClienteId>3</ClienteId>
<DtCadastro>2017-08-22T00:00:00</DtCadastro>
<Nome>Artefatos</Nome>
<RazaoSocial>Art e Fatos</RazaoSocial>
<TipoPessoa>PJ</TipoPessoa>
</Cliente>
<Cliente>
<ClienteId>4</ClienteId>
<DtCadastro>2017-08-22T00:00:00</DtCadastro>
<Nome>Empresa e Ind.</Nome>
<RazaoSocial>Nicks Oliveira</RazaoSocial>
<TipoPessoa>PJ</TipoPessoa>
</Cliente>
</ArrayOfCliente>

Model Cliente:

public class Cliente
    {
        public int ClienteId { get; set; }
        public string Nome { get; set; }
        public string RazaoSocial { get; set; }
        public string TipoPessoa { get; set; }
        public DateTime DtCadastro { get; set; }
    }

2 answers

2

You can use C#Serialization as steps below:

import of the class:

using System.Xml.Serialization;

Define your XML elements in the class:

[XmlRoot(ElementName = "ArrayOfCliente", Namespace = "http://schemas.datacontract.org/2004/07/Dominio.Apolo.Modelo")]
public class ArrayOfCliente
{
    [XmlElement("Cliente")]
    public List<cliente> cliente { get; set; }
}


public class cliente
{
    [XmlElement("ClienteId")]
    public int ClienteId { get; set; }

    [XmlElement("Nome")]
    public string Nome { get; set; }

    [XmlElement("RazaoSocial")]
    public string RazaoSocial { get; set; }

    [XmlElement("TipoPessoa")]
    public string TipoPessoa { get; set; }

    [XmlElement("DtCadastro")]
    public DateTime DtCadastro { get; set; }
}

After that, just call the C Xmlserializer#:

    XmlSerializer serializer = new XmlSerializer(typeof(ArrayOfCliente));
            using (TextReader reader = new StringReader(@"<ArrayOfCliente xmlns:i='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://schemas.datacontract.org/2004/07/Dominio.Apolo.Modelo'>
  <Cliente>
    <ClienteId>3</ClienteId>
    <DtCadastro>2017-08-22T00:00:00</DtCadastro>
    <Nome>Artefatos</Nome>
    <RazaoSocial>Art e Fatos</RazaoSocial>
    <TipoPessoa>PJ</TipoPessoa>
  </Cliente>
  <Cliente>
    <ClienteId>4</ClienteId>
    <DtCadastro>2017-08-22T00:00:00</DtCadastro>
    <Nome>Empresa e Ind.</Nome>
    <RazaoSocial>Nicks Oliveira</RazaoSocial>
    <TipoPessoa>PJ</TipoPessoa>
  </Cliente>
</ArrayOfCliente>"))
            {
                ArrayOfCliente result = (ArrayOfCliente)serializer.Deserialize(reader);
            }
  • I got it, @Damon Dudek I put the xml in the post for a better understanding and I was in doubt how to get this xml dynamically, something like that _clientes = response // dados do xml ?

  • just replace the string I put in Stringreader with your

  • Good morning @Damon Dudek implemented the solution again and there is type conversion error I edited the post and added an error print.

  • What’s coming to your answer? Debug the object

1

By default the . Net both in webapi and MVC brings a package called Newtonsoft.Json, with it it is possible to deserialize from json to an object and the code would look like below, but as your api is returning XML, first you would have to transform the xml into json.

NOTE: If your api can return json, your problem is solved with the code below:

private Cliente Listar()
{
    HttpResponseMessage response = _client.GetAsync("api/clientes").Result;
    Cliente _clientes = new Cliente();
    if (response.IsSuccessStatusCode)
    {
          _clientes = JsonConvert.DeserializeObject<Cliente>(response);                   
    }
    else
        Response.Write(response.StatusCode.ToString() + " - " + response.ReasonPhrase);

    return _clientes;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.