Home > Uncategorized > Using JsonReaderWriterFactory. CreateJsonReader in C#

Using JsonReaderWriterFactory. CreateJsonReader in C#

screen-shot-2017-04-17-at-114949-am

Whenever you want to read JSON in C#, I don’t normally look any further than Newtonsoft.Json , but if you are not allowed to use third-party libraries in your project, then there is a little known JSON parser built into .NET (or the System.Runtime.Serialization.Json library).

But, it’s not nice to use, and who wants to use XPath Queries with Json anyway, it’s awkward and unnatural!

So, I’ve written a class that does not use any third-party libraries, but uses a similar calling structure to Newtonsoft.JSON.

using System.Collections.Generic;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml.Linq;

namespace Synergy.Common
{
/// <summary>
/// A simplified version of JSON
/// </summary>
public class MyJson : Dictionary<string, MyJson>
{
/// <summary>
/// The value of the node
/// </summary>
public string Value;

// public Dictionary<string, MyJson> Children = new Dictionary<string, MyJson>();

/// <summary>
/// Parses the specified json.
/// </summary>
/// <param name=”json”>The json.</param>
/// <returns></returns>
public static MyJson Parse(string json)
{
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), new System.Xml.XmlDictionaryReaderQuotas());
var xe = XElement.Load(jsonReader);
return FromElement(xe);
}

private static MyJson FromElement(XContainer xe)
{
var root = new MyJson { Value = “” };
foreach (var element in xe.Elements())
{
if (root.ContainsKey(element.Name.LocalName)) continue; // Don’t support duplicates so far
root.Add(element.Name.LocalName,
element.HasElements ? FromElement(element) : new MyJson {Value = element.Value});
}
return root;
}
}
}

You call MyJson.Parse() passing in some JSON, and what you get back, is a nested dictionary, where each dictionary entry can have sub-dictionaries. If it has an empty sub-dictionary, then it will have a Value property set.

The Value property is always a string, so there is no fancy date or number parsing yet, and it does not allow duplicate keys.

Feel free to comment with improvements.

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: