JSON and XML

With the extensive use of internet and cloud applications, JSON and XML are becoming more important in terms of data transfer between applications. Using JSON and XML also increases the number of data-related issues, unless the data is validated. 

Schema validation can be used to validate an XML file, which will help us to identify whether XML is inline with data types defined. However, to validate the actual data, you may still be using the methods we discussed in this chapter. Visual Studio helps you to create a schema file. The Xsd.exe <XML file> command will create a schema file. Here is an example XML file.

This XML file has a Students root element, in which information is held in relation to multiple students. Each student element has child elements that hold values including FirstName, LastName, School, and DOB:

<?xml version="1.0" encoding="utf-8" ?>
<Students>
<student>
<FirstName>Student1</FirstName>
<LastName>Slast</LastName>
<School>School1</School>
<DOB>23/10/1988</DOB>
</student>
</Students>

Visual Studio allows us to create a schema for this XML. Open the XML file in Visual Studio and select the XML menu item. The Create Schema option will become available. Selecting this will create a .xsd schema:

The content of the Sample.xsd file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Students">
<xs:complexType>
<xs:sequence>
<xs:element name="student">
<xs:complexType>
<xs:sequence>
<xs:element name="FirstName" type="xs:string" />
<xs:element name="LastName" type="xs:string" />
<xs:element name="School" type="xs:string" />
<xs:element name="DOB" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

As you can see, names are defined as a string, as are dates. So when you access this date element, we may need to convert it in order to use it in our application.

Now, we will jump to some sample code and observe how to validate an XML file using a schema:

static void LoadXML()
{
var path = new Uri(Path.GetDirectoryName(System.
Reflection.Assembly.
GetExecutingAssembly().CodeBase)).LocalPath;
XmlSchemaSet schema = new XmlSchemaSet();
schema.Add("", path + "\sample.xsd");
XmlReader rd = XmlReader.Create(path + "\sample.xml");
XDocument doc = XDocument.Load(rd);
Console.WriteLine("Validating XML");
doc.Validate(schema, ValidationEventHandler);
Console.WriteLine("Validating XML Completed");
}
static void ValidationEventHandler(object sender,
ValidationEventArgs e)
{
XmlSeverityType type;
if (Enum.TryParse<XmlSeverityType>(e.Severity.ToString(), out
type))
{
if (type == XmlSeverityType.Error) throw new
Exception(e.Message);
}
}

As we passed a valid XML file, we did not encounter any issues validating it. However, when you try to remove any elements from it, such as removing the school from the XML file, then you encounter an error message. Try it yourself when you practice this lab so as to understand validation in greater detail:

Validating XML
Validating XML Completed
Press any key to exit.

When executed, this method either writes a message on the console to the effect that validation is complete, or it may throw an exception in the event of an error in the XML.

Another format we discussed is JSON. .NET Framework provides us with JSON serializers, which can be used to validate JSON. This is like creating a C# class, using a JSON serializer to convert a C# object to JSON, and then deserializing back to the C# object. It is similar to the .NET Framework serialization concept. However, not every JSON has a schema to serialize or deserialize. In this case, we will work on validating the JSON format. In the following example, we create a class serializer to convert a JSON object and then deserialize it back to an object.

Here, we are creating a class called Authors with three properties: AuthorName, Skills, and DOB. We will use this object to serialize and deserialize this object:

public class Authors
{
public string AuthorName { get; set; }
public string Skills { get; set; }
public DateTime DOB { get; set; }
}

In the next section, we created a new method where we used the Newtonsoft.Json namespace to convert the Authors object to JSON. You can get NewtonSoft.Json using NuGet packages:

static string GetJson()
{
string result = string.Empty;
Authors aclass = new Authors() { AuthorName = "Author1", Skills =
"C#,Java,SQL", DOB = DateTime.Now.Date };
result = JsonConvert.SerializeObject(aclass);
Console.WriteLine($"JSON object : {result}");
return result;
}

Next, we will convert JSON to the Authors object using the JSON.Deserialize method:

static Authors GetObject(string result)
{
Authors aresult = JsonConvert.DeserializeObject<Authors>(result);
Console.WriteLine($"Name: {aresult.AuthorName}, Skills =
{aresult.Skills},
DOB = {aresult.DOB}");
return aresult;
}

Following is the program that invokes both these methods. Initially, we invoke the GetJSON method to get the Json string, and then use this string to convert it to an Authors object using the GetObject method. In the second line, we modify the string result that we got in the first line, and try to deserialize it. This operation will throw an exception. 

In the following, we are trying to modify the .json results by concatenating text called Test. This is what happens when you modify the .json object and try to deserialize it to an Authors object:

string result = GetJson();
Authors a = GetObject(result);
string result1 = string.Concat(result, "Test");
Console.ReadLine();
Authors a1 = GetObject(result1);

The following output shows the JSON object that we converted from the Authors object, followed by the Author object that we deserialized from the JSON object:

JSON object : {"AuthorName":"Author1","Skills":"C#,Java,SQL","DOB":"2019-03-31T00:00:00+11:00"}
Name: Author1, Skills = C#,Java,SQL, DOB = 3/31/2019 12:00:00 AM
Press any key to exit.

Here is the exception that the program throws when we modify JSON and try to deserialize it to an Authors object:

This is an example where we try to validate a JSON object. If it gets modified during transmission, this can be identified during the deserialization process.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.199.184