繁体   English   中英

Null object 反序列化时 C#

[英]Null object when deserializing C#

我正在尝试将 XML 请求转换为 C #object,但我不能。 我尝试了几种 StackOverFlow 解决方案,但都没有奏效。 有谁知道它可能是什么? 因为 object 上的 Header 是 null,所以在请求中有更多标签,但我正在逐步组装它。

我不知道它是否有区别,但在 Header class 我将 XmlRoot 标签更改为 XmlElement 并继续而不反序列化

我有以下文件和 function

文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace BonzayBO.DTO
{
[XmlRoot("Conciliation")]
public class Conciliation
{
    [XmlElement("Header")]
    Header Header { get; set; }
}

  [XmlRoot("Header")]
  public class Header
  {
    [XmlElement("GenerationDateTime")]
    string GenerationDateTime { get; set; }
    [XmlElement("StoneCode")]
    int StoneCode { get; set; }
    [XmlElement("LayoutVersion")]
    int LayoutVersion { get; set; }
    [XmlElement("FileId")]
    int FileId { get; set; }
    [XmlElement("ReferenceDate")]
    string ReferenceDate { get; set; }

  }
}

功能:

public string BuscarConciliacaoDiaCliente()
    {
        using (BDBONZAY bd = new BDBONZAY())
        {
            try
            {
                using (HttpClient requisicao = new HttpClient())
                {
                    var resposta = requisicao.GetAsync("https://gabriel.free.beeceptor.com/bonzay").Result;

                    if (resposta.StatusCode == HttpStatusCode.OK)
                    {
                        var xml = new XmlDocument();
                        xml.LoadXml(resposta.Content.ReadAsStringAsync().Result);
                                                    
                        bd.BeginTransaction();

                        XmlSerializer serializer = new XmlSerializer(typeof(BonzayBO.DTO.Conciliation));
                        using (TextReader reader = new StringReader(resposta.Content.ReadAsStringAsync().Result))
                        {
                            BonzayBO.DTO.Conciliation result = (BonzayBO.DTO.Conciliation)serializer.Deserialize(reader);
                        }
                        
                        bd.CommitTransaction();
                    }
                }
            }
            catch (Exception ex)
            {
                bd.RollbackTransaction();
                throw;
            }
        }
        return "";
    }

XML:

<?xml version="1.0" ?>
<Conciliation>
    <Header>
        <GenerationDateTime>20151013145131</GenerationDateTime>
        <StoneCode>123456789</StoneCode>
        <LayoutVersion>2</LayoutVersion>
        <FileId>020202</FileId>
        <ReferenceDate>20150920</ReferenceDate>
    </Header>
    <FinancialTransactions>
        <Transaction>
            <Events>
                <CancellationCharges>0</CancellationCharges>
                <Cancellations>1</Cancellations>
                <Captures>0</Captures>
                <ChargebackRefunds>0</ChargebackRefunds>
                <Chargebacks>0</Chargebacks>
                <Payments>0</Payments>
            </Events>
            <AcquirerTransactionKey>12345678912356</AcquirerTransactionKey>
            <InitiatorTransactionKey>1117737</InitiatorTransactionKey>
            <AuthorizationDateTime>20150818155931</AuthorizationDateTime>
            <CaptureLocalDateTime>20150818125935</CaptureLocalDateTime>
            <Poi>
                <PoiType>4</PoiType>
            </Poi>
            <EntryMode>1</EntryMode>
            <Cancellations>
                <Cancellation>
                    <OperationKey>3635000017434024</OperationKey>
                    <CancellationDateTime>20150920034340</CancellationDateTime>
                    <ReturnedAmount>20.000000</ReturnedAmount>
                    <Billing>
                        <ChargedAmount>19.602000</ChargedAmount>
                        <PrevisionChargeDate>20150921</PrevisionChargeDate>
                    </Billing>
                </Cancellation>
            </Cancellations>
        </Transaction>   
    </FinancialTransactions>
    <Payments>
        <Payment>
            <Id>109863</Id>
            <WalletTypeId>1</WalletTypeId>
            <TotalAmount>840.72</TotalAmount>
            <TotalFinancialAccountsAmount>840.72</TotalFinancialAccountsAmount>
            <LastNegativeAmount>0.00</LastNegativeAmount>
            <FavoredBankAccount>
                <BankCode>1</BankCode>
                <BankBranch>24111</BankBranch>
                <BankAccountNumber>0123456</BankAccountNumber>
            </FavoredBankAccount>
        </Payment>
    </Payments>
    <Trailer>
        <CapturedTransactionsQuantity>2</CapturedTransactionsQuantity>
        <CanceledTransactionsQuantity>2</CanceledTransactionsQuantity>
        <PaidInstallmentsQuantity>3</PaidInstallmentsQuantity>
        <ChargedCancellationsQuantity>1</ChargedCancellationsQuantity>
        <ChargebacksQuantity>2</ChargebacksQuantity>
        <ChargebacksRefundQuantity>1</ChargebacksRefundQuantity>
        <ChargedChargebacksQuantity>1</ChargedChargebacksQuantity>
        <PaidChargebacksRefundQuantity>1</PaidChargebacksRefundQuantity>
        <PaidEventsQuantity>1</PaidEventsQuantity>
        <ChargedEventsQuantity>1</ChargedEventsQuantity>
    </Trailer>
</Conciliation>

序列化不起作用,因为您的 class 成员是private的,而 xml 序列化仅适用于公共成员。 你需要做的第一个改变是让你的成员,描述 xml 结构,公开:

来自docs.microsoft.comClass members can have any of the five kinds of declared accessibility and default to private declared accessibility

public class Conciliation
{
    [XmlElement("Header")]
    public Header Header { get; set; }
}

public class Header
{
    [XmlElement("GenerationDateTime")]
    public string GenerationDateTime { get; set; }
    [XmlElement("StoneCode")]
    public int StoneCode { get; set; }
    [XmlElement("LayoutVersion")]
    public int LayoutVersion { get; set; }
    [XmlElement("FileId")]
    public int FileId { get; set; }
    [XmlElement("ReferenceDate")]
    public string ReferenceDate { get; set; }

}

反序列化实际上很短。 示例 XML 可以使用以下代码进行反序列化:

using (var fs = new FileStream(@"c:\temp\xml1.xml", FileMode.Open))
{
    var xmls = new XmlSerializer(typeof(Conciliation));
    var xmlStructure = ((Conciliation)xmls.Deserialize(fs));
    xmlStructure.Dump();
}

解析的值如下所示:

在此处输入图像描述

制作一个反序列化字符串输入的小方法,并在您的BuscarConciliacaoDiaCliente()中使用它。

例如:

private Conciliation deserializeXml(string xmlContent)
{
    using (var fs = (TextReader)new StringReader(xmlContent))
    {
        var xmls = new XmlSerializer(typeof(Conciliation));
        var conciliation = ((Conciliation)xmls.Deserialize(fs));
        return conciliation;
    }
}

将 resposta.Content.ReadAsStringAsync resposta.Content.ReadAsStringAsync().Result的内容作为xmlContent传递。

我不详细了解您的逻辑,但是 IMO 您的 function 可以写成如下:

public string BuscarConciliacaoDiaCliente()
{
    using (BDBONZAY bd = new BDBONZAY())
    {
        try
        {
            using (HttpClient requisicao = new HttpClient())
            {
                var resposta = requisicao.GetAsync("https://gabriel.free.beeceptor.com/bonzay").Result;
                
                if (resposta.StatusCode == HttpStatusCode.OK)
                {
                    //var xml = new XmlDocument();
                    //xml.LoadXml(resposta);

                    bd.BeginTransaction();
                    
                    Conciliation result = deserializeXml(resposta);

                    //XmlSerializer serializer = new XmlSerializer(typeof(Conciliation));
                    //using (TextReader reader = new StringReader(resposta))
                    //{
                    //  Conciliation result = (Conciliation)serializer.Deserialize(reader);
                    //}

                    bd.CommitTransaction();
                }
            }
        }
        catch (Exception ex)
        {
            bd.RollbackTransaction();
            throw;
        }
    //}
    return "";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM