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

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:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, General .NET and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.