-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:
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;
}
}
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; }
}
}
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.
– Carltee
Putz really is! It might be the XML structure... because it has the cServico node before the other nodes...
– Gabriel Peterossi Maricato
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
– Carltee