简体   繁体   English

为什么使用DataContractJsonSerializer序列化后的数组显示为空?

[英]Why are arrays being shown as null after serializing using DataContractJsonSerializer?

There have been a number of questions about serializing and deserializing arrays using DataContractJsonSerializer (including one from me: How can I serialise a string array to JSON using DataContractJsonSerializer? ) but none seem to answer the current problem that I'm having. 关于使用DataContractJsonSerializer序列化和反序列化数组存在很多问题(包括我的一个问题: 如何使用DataContractJsonSerializer将字符串数组序列化为JSON? ),但似乎没有一个问题可以回答我当前遇到的问题。

I am converting an XML string to a JSON string by deserializing the XML to a DataContract object and then serializing that object to JSON, using DataContractJsonSerializer. 通过将XML反序列化为DataContract对象,然后将该对象序列化为JSON,我使用DataContractJsonSerializer将XML字符串转换为JSON字符串。 My approach is the same as I have used on a number of other objects, all of which are serializing to JSON perfectly, but I have an object in which an array property is always rendered as null after serialization. 我的方法与我在许多其他对象上使用的方法相同,所有这些对象都已完美地序列化为JSON,但是我有一个对象,其中序列化后数组属性始终呈现为null。

The classes are defined as follows:- 这些类的定义如下:

[DataContract]
public class Order
{
    [DataMember(Name = "consignments")]
    [XmlElement("consignments")]
    public Consignment[] Consignments { get; set; }
}

[DataContract]
public class Consignment
{
    [DataMember(Name = "conh_id")]
    [XmlElement("conh_id")]
    public string ConsignmentHeaderId { get; set; }

    [DataMember(Name = "conh_status")]
    [XmlElement("conh_status")]
    public string ConsignmentHeaderStatus { get; set; }

    [DataMember(Name = "consignmententries")]
    [XmlElement("consignmententries")]
    public ConsignmentEntry[] ConsignmentEntries { get; set; }
}

The XML I'm using looks like this:- 我正在使用的XML看起来像这样:

<order>
  <consignments>
    <consignment>
      <conh_id>A19708176</conh_id>
      <conh_status>ACCEPTED</conh_status>
      <consignmententries>
        <consignmententry>
          <conl_lineNbr>10000</conl_lineNbr>
          <conl_sku>SEC01XXZBUXXX</conl_sku>
          <conl_original_qty>1</conl_original_qty>
        </consignmententry>
      </consignmententries>
    </consignment>
  </consignments>
</order>

The deserializing and serializing is done in the following methods:- 反序列化和序列化通过以下方法完成:

private object DeserialiseXml(string xml)
{
    var serialiser = new XmlSerializer(typeof(Order));
    var stringReader = new StringReader(xml);
    var result = serialiser.Deserialize(stringReader);

    return result;
}

private string SerialiseJson(object serialisable)
{
    using (MemoryStream stream = new MemoryStream())
    {
        var serialiser = new DataContractJsonSerializer(serialisable.GetType());
        serialiser.WriteObject(stream, serialisable);
        var json = Encoding.UTF8.GetString(stream.ToArray());

        return json;
    } 
}

When I test it, the Consignments property is always null in the resulting JSON. 当我对其进行测试时,结果JSON中的Consignments属性始终为null。

"order": {
  "consignments": [
    {
      "conh_id": null,
      "conh_status": null,
      "consignmententries": null
    }
  ]
}

Debugging shows that this property is null in the object created after the deserialization step so the problem is in the XML deserialization rather than the JSON serialization. 调试显示,在反序列化步骤之后创建的对象中,此属性为null,因此问题出在XML反序列化而不是JSON序列化上。

What do I need to change on my object model to get the array converted properly? 我需要对对象模型进行哪些更改才能正确转换数组?

Your problem is happening when you deserialize from XML rather than when you serialize to JSON. 从XML反序列化而不是序列化为JSON时会发生问题。 In your XML, the collections have been serialized with two levels: an outer container element and an element for each item: 在您的XML中,集合已被序列化为两个级别:一个外部容器元素和一个用于每个项目的元素:

  <consignments>
    <consignment>
       <!-- Consignment data -->
    </consignment>
  </consignments>

And

  <consignmententries>
    <consignmententry>
       <!-- Entry data -->
    </consignmententry>
  </consignmententries>

(For comparison, in the linked question the Labels XML collection has a single level). (为了进行比较,在链接的问题中Labels XML集合具有单个级别)。 Thus you need to use [XmlArray(string name)] and [XmlArrayItem(string itemName)] to specify the outer and inner element names: 因此,您需要使用[XmlArray(string name)][XmlArrayItem(string itemName)]指定外部和内部元素名称:

[DataContract]
[XmlRoot("order")]
public class Order
{
    [DataMember(Name = "consignments")]
    [XmlArray("consignments")]
    [XmlArrayItem("consignment")]
    public Consignment[] Consignments { get; set; }
}

[DataContract]
public class Consignment
{
    [DataMember(Name = "conh_id")]
    [XmlElement("conh_id")]
    public string ConsignmentHeaderId { get; set; }

    [DataMember(Name = "conh_status")]
    [XmlElement("conh_status")]
    public string ConsignmentHeaderStatus { get; set; }

    [DataMember(Name = "consignmententries")]
    [XmlArray("consignmententries")]
    [XmlArrayItem("consignmententry")]
    public ConsignmentEntry[] ConsignmentEntries { get; set; }
}

Conversely, adding the attribute [XmlElement] to a collection tells XmlSerializer that the collection should be serialized without the outer container element. 相反,向集合添加属性[XmlElement]告诉XmlSerializer ,该集合应在没有外部容器元素的情况下进行序列化。

You also need to add [XmlRoot("order")] to Order to specify the root element name. 您还需要将[XmlRoot("order")]Order以指定根元素名称。

Now your XML will deserialize successfully. 现在,您的XML将成功反序列化。

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

相关问题 使用DataContractJsonSerializer序列化Dictionary &lt;&gt;对象 - Serializing a Dictionary<> object with DataContractJsonSerializer 使用datacontractjsonserializer在dataTable中序列化图像 - Serializing an image in a dataTable with datacontractjsonserializer DataContractJsonSerializer无法正确序列化 - DataContractJsonSerializer not serializing properly 为什么序列化对象列表后所有值都为空? - Why are all values null after serializing the object list? DataContractJsonSerializer:使用接口属性序列化一个类 - DataContractJsonSerializer: Serializing a class with an interface property 使用 DataContractJsonSerializer 序列化时出现 InvalidDataContractException - Getting InvalidDataContractException while serializing with DataContractJsonSerializer 防止使用datacontractjsonserializer C#序列化一个propery - prevent a propery from being serialized using a datacontractjsonserializer C# 使用DataContractJsonSerializer添加反斜杠序列化具有Web URL到JSon的字符串 - Serializing string which has web url to JSon using DataContractJsonSerializer adding backslashes DataContractJsonSerializer返回空对象 - DataContractJsonSerializer returning null object 为什么分配此对象后该对象为null? - Why is this object null after being assigned?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM