简体   繁体   English

XML反序列化返回Null值

[英]XML DeSerialization returning Null values

I have a POST method in a web api that has a RequestAppointment paramater. 我在具有RequestAppointment参数的Web API中有一个POST方法。 For example: 例如:

 // POST: api/RequestAppointment
            public HttpResponseMessage Post([FromBody]RequestAppointment httpRequest)
            {
                var response = Appointment.CreateAppointment(httpRequest);

                return Request.CreateResponse<ResponseRequest>(System.Net.HttpStatusCode.Created, response); 
            } 

RequestAppoint class has this structure: RequestAppoint类具有以下结构:

public partial class RequestAppointment
    {
        public RequestAppointmentAppointmentInformation appointmentInformation { get; set; }      
    }
    public partial class RequestAppointmentAppointmentInformation
    {
        public string AppointmentCcEmail { get; set; }        
        public string ClaimType { get; set; }       
        public RequestAppointmentAppointmentInformationClaimant Claimant { get; set; }

    }
    public partial class RequestAppointmentAppointmentInformationClaimant
    {
        public System.DateTime DateOfBirth { get; set; }        
    }

Two requests are possible to be made: 1st one is : 可以提出两个请求:第一个是:

<RequestAppointment>
  <appointmentInformation>
    <AppointmentCcEmail>x.x.com</AppointmentCcEmail>   
    <ClaimType>A</ClaimType>
    <Claimant>
      <DateOfBirth>1961-12-25</DateOfBirth>
    </Claimant>
  </appointmentInformation>
</RequestAppointment>

2nd Request is: 第二个请求是:

<RequestAppointment>
  <appointmentInformation>
    <AppointmentCcEmail>x.x.com</AppointmentCcEmail>   
    <ClaimType>A</ClaimType>   
  </appointmentInformation>
</RequestAppointment>

The difference between the two request XML is that #1 has Claimant tag while the #2 does not have. 两种请求XML之间的区别在于,#1没有Claimant标签,而#2没有。

The 2nd request does not have because the claimant is not supplied when users call the web service from data interface. 第二个请求没有,因为当用户从数据接口调用Web服务时未提供索赔人。 While the first will always have when Claimant is supplied. 提供索赔人时,第一个总是有。

On my testing using Fiddler, my #1 request returns data. 在使用Fiddler进行测试时,我的#1请求返回了数据。 That is, it is able to deserialize into the object RequestAppointment, while #2 request returns null values. 也就是说,它能够反序列化到对象RequestAppointment中,而#2 request返回空值。

What can I do to resolve this issue? 我该怎么做才能解决这个问题? The request will always come in those two formats and they will always use the same model structure. 该请求将始终以这两种格式出现,并且它们将始终使用相同的模型结构。

What can I do to solve this issue? 我该怎么做才能解决这个问题? I tested the scenario in Fiddler. 我在Fiddler中测试了该方案。

First of all, step 1. if you have RequestAppointment XSD file, the best solution is to generate class using xsd.exe see haw to use it , if not you can create XSD yourself and do step 1, or finally you should make changes and point explicit attributes making your class XML serializable. 首先,执行步骤1。如果您有RequestAppointment XSD文件,最好的解决方案是使用xsd.exe生成类, 请参阅使用它的方法 ;否则,您可以自己创建XSD并执行步骤1,否则最后应该进行更改并点显式属性,使您的类XML可序列化。 There is a lot of article about it. 关于它的文章很多。

This class generated with xsd.exe , I create sample schema from you XML, made changes only in tag <Claimant> making it optional, and class looks like this. 使用xsd.exe生成的此类,我从您的XML创建示例架构,仅在标记<Claimant>进行了更改,使其变为可选,并且该类如下所示。 Pay attention how tool generates optional field Claimant 注意工具如何生成可选字段Claimant

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.6.1055.0.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class RequestAppointment {

    private RequestAppointmentAppointmentInformation appointmentInformationField;

    /// <remarks/>
    public RequestAppointmentAppointmentInformation appointmentInformation {
        get {
            return this.appointmentInformationField;
        }
        set {
            this.appointmentInformationField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class RequestAppointmentAppointmentInformation {

    private string appointmentCcEmailField;

    private string claimTypeField;

    private RequestAppointmentAppointmentInformationClaimant claimantField;

    /// <remarks/>
    public string AppointmentCcEmail {
        get {
            return this.appointmentCcEmailField;
        }
        set {
            this.appointmentCcEmailField = value;
        }
    }

    /// <remarks/>
    public string ClaimType {
        get {
            return this.claimTypeField;
        }
        set {
            this.claimTypeField = value;
        }
    }

    /// <remarks/>
    public RequestAppointmentAppointmentInformationClaimant Claimant {
        get {
            return this.claimantField;
        }
        set {
            this.claimantField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class RequestAppointmentAppointmentInformationClaimant {

    private System.DateTime dateOfBirthField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="date")]
    public System.DateTime DateOfBirth {
        get {
            return this.dateOfBirthField;
        }
        set {
            this.dateOfBirthField = value;
        }
    }
}

XSD example XSD示例

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="RequestAppointment">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="appointmentInformation">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="AppointmentCcEmail" type="xs:string" />
              <xs:element name="ClaimType" type="xs:string" />
              <xs:element name="Claimant" minOccurs="0">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="DateOfBirth" type="xs:date" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Thanks for all your suggestions. 感谢您的所有建议。 They are great! 他们都是伟大的! Seyran's answers really proved awesome. Seyran的回答确实很棒。 But in the case of my question, I solved it by nil="true" (nullable=true) to all the elements. 但是对于我的问题,我通过对所有元素使用nil =“ true”(nullable = true)来解决。 And I used the xsd to generate the classes for my request xml. 我使用xsd为我的请求xml生成类。

Thanks 谢谢

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

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