Sunday, August 09, 2009

Json.NET and Its Usage (3)

In this blog, I'l continue to the issues related to XML. In many cases, I have XML strings as data source, such as configuration files, and data in the format of XML from ADO.Net. JSon.Net provides some APIs to convert from XML to Json strings or vice versa. Based on those APIs, I have added some methods to my wrap class.

The first method is to convert from a Json string to an XML string:

public static string ConvertToXMLString(string jsonString)
{
  XmlNode xmlNode = JsonConvert.DeserializeXmlNode(jsonString);
  string xmlString = xmlNode.OuterXml;
  
  return xmlString;
}

Note: make sure the JsonString must have a single root item on top. If the JsonString contains more than one property values at the top or root, this conversion will throw exception since the converted XML has to have a single root node.

The opposite method is to convert an XML string to a JsonString:

public static string ConvertToJsonString(string xmlString)
{
  var xmlDoc = new XmlDocument();
  xmlDoc.Load(new StringReader(xmlString));
  string jsonString = JsonConvert.SerializeXmlNode(xmlDoc.DocumentElement);

  return jsonString;
}

public static string ConvertToFormattedJsonString(
    string xmlString,
    bool quoteName)
{
  string jsonStr;
  using (MemoryStream msJson = new MemoryStream(xmlString.StrToByteArray()))
  {
    using (MemoryStream ms = new MemoryStream())

    {
       using (JsonTextWriter jtw = new JsonTextWriter(new StreamWriter(ms)))
       {
          jtw.QuoteName = quoteName;
          jtw.Formatting = Newtonsoft.Json.Formatting.Indented;
          jtw.WriteToken(new JsonTextReader(new StreamReader(msJson)));

          jtw.Flush();

          ms.Flush();
          ms.Position = 0;
          using (StreamReader sr = new StreamReader(ms))
          {
              jsonStr = sr.ReadToEnd();
          }
       }
    }
  }

  return jsonStr.Replace(@"\r\n", Environment.NewLine);
}

Depending on the usage, you may need to get a nice formatted JsonString or just a long JsonString.

One reason I added some XML API methods in my wrapper class is that I find out it is very easy to manipulate XML strings by using XML Parser or XMLDoc class. For example, when I get an XML string from a configuration file, before I convert it to an instance, I have to prepare the XML in a correct format. By the time I got Json.Net library, the library did not support XML string with comments(the author promised to handle this issue), So I have to remove all the comments before converting the XML string to JsonString.

Another example is that I may have only one node in XML file as a property value. However, to convert the property value to an array of property values, I have to add a dummy node to XML file so that the JsonString from XML file will be in the correct layout before I map it to an instance. Therefore, I have the following API methods to cover those cases:


public static int AddNewNodeToRefNode(
  ref string xmlString,
  string refNodeXPath,
  string newNodeName,
  string newInnerText,
  bool beforeOrAfter,

  bool firstOrAll)
{
  //  Add a new node to a reference node
  //  ...
}

public static int AddNewNodeToRefNodeAsChildNode(
  ref string xmlString,
  string refNodeXPath,

  string newNodeName,
  string newInnerText,
  bool firstOrLastChildren,
  bool firstOrAll)
{
  // Add new node as a child node to a reference node]
  // ...
}

public static int GetXMLNodesCount(

  string xmlString,
  string nodeXPath)
{
  // Get count of a node in XML string
  // Use this method get count before adding new dummy nodes
  // ...
}

public static string RemoveComments(
  string xmlString)
{

  // Remove all comments in XML string
  // ...
}

public static bool UpdateXMLNodes(
  ref string xmlString,
  string nodeXPath,
  string newInnerText,
  bool firstNodeOrAll)
{

  // Use this method to update XML node content
  // if you use XML as input to JsonString then to Instance
  // and save the changes in Instance back to XML
  // ...
}


This is the conclusion of my serials of brief introduction of Json.Net library and my wrapper class. I'll continue to provide some examples about how to use the library.

0 comments: