Saturday, March 9, 2019

XML to C# Objects using JSON - Translate List of Objects


Let’s presume that there is an XML Array like this.

<Books>
<Book>
 <Name>Book Name 1</Name>
 <Author>Author 1</Author>
</Book>
<Book>
 <Name>Book Name 2</Name>
 <Author>Author 2</Author>
</Book>
<Book>
 <Name>Book Name 3</Name>
 <Author>Author 3</Author>
</Book>
</Books>

You can extract the data into C# objects using XML serialization. But XML Serialization will only work if the outer most element is like this.

<ArrayOfBook></ArrayOfBook>

For some reason, if your XML from the SQL server is not like this then you have to use XML attributes in the class definition of “Book” correctly and also create a collection class for the Book List.

The other alternative is to use Newtonsoft JSON. Here is the function to do it.

if (!string.IsNullOrEmpty(inXMLString))
{
    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
    doc.LoadXml(inXMLString); // Use this line if there is already XML content in a string.
    string jsonText = JsonConvert.SerializeXmlNode(doc);
    dynamic dynObject = JsonConvert.DeserializeObject(jsonText);
    foreach (dynamic innerContents in dynObject.Books)
    {
        List<Book> listOfBooks = new List<Book>();
        string jstring = JsonConvert.SerializeObject(innerContents.Value);
        if (innerContents.Value is JArray)
        {
            listOfBooks = JsonConvert.DeserializeObject<List<Book>>(jstring);
        }
        if (innerContents.Value is JObject)
        {
            Book oneBook = JsonConvert.DeserializeObject<Book>(jstring);
            listOfBooks.Add(oneBook);
        }
       togoBooks.AddRange(listOfBooks);
    }
}

return togoBooks;

Hope this helps. Happy coding.

No comments:

Post a Comment

All Blogs so far ...