Deserialize XML for object comes with null information

Asked

Viewed 63 times

-1

I am having trouble trying to deserialize an XML returned by the webservice to an object in my project, what happens is that the object is created, but with all properties without value (nulls).

The XML I want has a very simple structure:

Web service

When making the request, I get this data and convert it to XML, according to the code below:

public async Task<CorreioResult> CalcularFrete()
    {
        string url = $"{baseUrl}?nCdEmpresa=&sDsSenha=&sCepOrigem=09020240&sCepDestino=07070000&nVlPeso=1&nCdFormato=1&nVlComprimento=20&nVlAltura=20&nVlLargura=20&sCdMaoPropria=N&nVlValorDeclarado=2000&sCdAvisoRecebimento=N&nCdServico=04014&nVlDiametro=20&StrRetorno=xml&nIndicaCalculo=3";
        CorreioResult result = null;
        var response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            string resultado = await response.Content.ReadAsStringAsync();
            result = ConverterParaXml(resultado);
        }
        return result;
    }

    private CorreioResult ConverterParaXml(string data)
    {

        var buffer = Encoding.UTF8.GetBytes(data);
        using (var stream = new MemoryStream(buffer))
        {
            var serializer = new XmlSerializer(typeof(CorreioResult));
            var resultado = (CorreioResult)serializer.Deserialize(stream);
            return resultado;
        }

    }

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

However, my Correioresult object always comes with null values. Below is the class Correioresult:

using System;
using System.Xml.Serialization;

namespace LojaVirtual.Models
{
[XmlRoot("Servicos")]           
[Serializable()]    
public class CorreioResult
{
    [XmlElement(ElementName = "Codigo")]
    public string Codigo { get; set; }

    [XmlElement(ElementName = "valor")]
    public int Valor { get; set; }

    [XmlElement(ElementName = "PrazoEntrega")]
    public string PrazoEntrega { get; set; }

    [XmlElement(ElementName = "ValorSemAdicionais")]
    public string ValorSemAdicionais { get; set; }

    [XmlElement(ElementName = "Erro")]
    public string Erro { get; set; }
}  

}

2 answers

0

Good afternoon!

I believe the code below works for you:

  private CorreioResult ConverterParaXml(string data)
    {
        using (TextReader reader = new StreamReader(data))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(CorreioResult));
            return (CorreioResult) serializer.Deserialize(reader);
        }
    }

Hugs!

  • Hello, using Streamreader I have an exception of type System.IO.Exception, because it searches a file in the path of my data parameter, and this file does not exist.

  • Putz really is! It might be the XML structure... because it has the cServico node before the other nodes...

  • Exactly, I tried to refactor my Correioresult class to be with exactly the same XML structure, but I had no results, perhaps because I have no experience with xml

0

Problem solved.

My query was returning an object within the , which is the cServico, so as I reflected this in my class everything worked as it should.

Follow the code below for anyone interested.

//deve estar exatamente igual ao web service
[XmlRoot(ElementName = "Servicos")]
[Serializable()]
public class CorreioResult
{
    //deve estar exatamente igual ao web service
    [XmlElement(ElementName = "cServico")]
    public CorreioResultItem CorreioResultItem { get; set; } 
}

[Serializable()]
public class CorreioResultItem
{
    [XmlElement(ElementName = nameof(Codigo))]
    public int Codigo { get; set; }

    [XmlElement(ElementName = nameof(Valor))]
    public string Valor { get; set; }
    
    [XmlElement(ElementName = nameof(PrazoEntrega))]
    public int PrazoEntrega { get; set; }

    [XmlElement(ElementName = nameof(ValorSemAdicionais))]
    public string ValorSemAdicionais { get; set; }

    [XmlElement(ElementName = nameof(Erro))]
    public int Erro { get; set; }
}

}

Browser other questions tagged

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