Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

Deserialize XML array to string[] and how to allow JSON to be deserialized into the same POCO class

$
0
0

How do you deserialize the classic XML array to an string[] type?

The XML representation of an array is a list of elements:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <MyXml>
      <Id>657467</Id>
	  <MyArray>
	    <element>A</element>
	    <element>B</element>
	    <element>C</element>
	  </MyArray>
   </MyXml>
</root>

And the MyArray would normally be deserialized to an annoying class:

// I don't want this class
[XmlRoot(ElementName="MyArray")]
public class MyArray 
{
  [XmlElement(ElementName="element")]
  public List<string> Element { get; set; }
}

// I Just want a string array:
public string[] MyArray { get; set; }

The solution is to use the XmlArray and XmlArrayItem attributes. These properties specifies that the XmlSerializer must serialize the XML structure as an array:

[XmlArray(ElementName = "MyArray", IsNullable = true)]
[XmlArrayItem(ElementName = "element", IsNullable = true)]
public string[] Myarray 
{
  get; set;
}

The XmlArray attribute determines that the MyArray XML element is an array, and the XmlArrayItem attribute determines that each array element is called element in the XML.

Now, the XmlSerializer will serialize the element to an array:

string contents = "this is my xml string";

XmlSerializer serializer = new XmlSerializer(typeof(MyXml));
using (TextReader reader = new StringReader(contents))
{
  var myclass = (MyXml)serializer.Deserialize(reader);
}

SO WHY IS THIS IMPORTANT?

This is important if you import XML and JSON, because you would rather not have to define this JSON just to cope with the XML array format:

"MyArray": {
  "element": [
    "A",
    "B",
    "C"
  ]

Instead, if you just decorate your POCO class with both XML and JSON properties:

[JsonProperty(PropertyName = "MyArray")]
[XmlArray(ElementName = "MyArray", IsNullable = true)]
[XmlArrayItem(ElementName = "element", IsNullable = true)]
public string[] Myarray 
{
  get; set;
}

You can use the proper JSON array notation:

"MyArray": [    
    "A",
    "B",
    "C"
]

MORE TO READ:


Viewing all articles
Browse latest Browse all 285

Trending Articles