Found a good articale on JSON Serialization and Deserialization:

http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET

I used this article to create a class that serializes DataSet, DataTable and DataRow objects:

I just changed one aspect of the codeproject article, I used the regular expression "\\/Date\((-?\d+)\)\\/" instead of  “\\/Date\((\d+)\+\d+\)\\/”. The regular expression “\\/Date\((-?\d+)\)\\/” takes into account dates before epoch (1979-1-1).

/// <summary>
/// Contains JSON helper functions.
/// </summary>
public class JsonHelper
{
    /// <summary>
    /// Date time format, used to convert a datetime to a string.
    /// By default "yyyy-MM-dd HH:mm:ss".
    /// </summary>
    public string DateTimeFormat { get; set; }

    /// <summary>
    /// Initializes properties.
    /// </summary>
    public JsonHelper()
    {
        DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    }

    /// <summary>
    /// Converts a DataSet to a JSON string.
    /// </summary>
    /// <param name="dataSet">The dataset to convert.</param>
    /// <exception cref="System.ArgumentException">Thrown when parameter [dataSet] is null.</exception>
    /// <returns>
    /// - JSON in the format [[[Table0Row0Column0,Table0Row0Column1],[Table0Row1Column0,Table0Row1Column1]],[[Table1Row0Column0,Table1Row0Column1],[Table1Row1Column0,Table1Row1Column1]]]
    /// - Empty string, when dataset contains no tables.
    /// - Empty string, when all tables contain no rows.
    /// </returns>
    public string ToJson(DataSet dataSet)
    {
        if (dataSet == null) { throw new ArgumentNullException("dataSet"); }

        StringBuilder result = new StringBuilder(string.Empty);
        if (dataSet.Tables.Count > 0)
        {
            result.Append("[");
            foreach (DataTable table in dataSet.Tables)
            {
                result.Append(ToJson(table));
            }
            result.Append("]");
        }
        return result.ToString();
    }

    /// <summary>
    /// Converts a DataTable to a JSON string.
    /// </summary>
    /// <param name="table">The dataset to convert.</param>
    /// <exception cref="System.ArgumentException">Thrown when parameter [table] is null.</exception>
    /// <returns>
    /// - JSON in the format JSON in the format [[Row0Column0,Row0Column1],[Row1Column0,Row1Column1]]
    /// - Empty string, when datatable contains no rows.
    /// </returns>
    public string ToJson(DataTable table)
    {
        if (table == null) { throw new ArgumentNullException("table"); }

        StringBuilder result = new StringBuilder(string.Empty);
        if (table.Rows.Count > 0)
        {
            result.Append("[");
            foreach (DataRow row in table.Rows)
            {
                result.Append(ToJson(row));
            }
            result.Append("]");
        }
        return result.ToString();
    }

    /// <summary>
    /// Converts a DataRow to a JSON string.
    /// </summary>
    /// <param name="row">The data row to convert.</param>
    /// <exception cref="System.ArgumentException">Thrown when parameter [row] is null.</exception>
    /// <exception cref="System.ArgumentException">Thrown when property [DateTimeFormat] is null, empty or contains only whitespaces.</exception>
    /// <returns>
    /// - JSON in the format [Row0Column0,Row0Column1].
    /// - Empty string, when datarow contains no columns.
    /// </returns>
    public string ToJson(DataRow row)
    {
        if (row == null) { throw new ArgumentNullException("row"); }
        if (string.IsNullOrWhiteSpace(DateTimeFormat)) { throw new ArgumentNullException("DateTimeFormat"); }

        StringBuilder result = new StringBuilder(string.Empty);
        if (row.ItemArray.Count() > 0)
        {
            var serializer = new JavaScriptSerializer();
            string json = serializer.Serialize(row.ItemArray);

            // Replace Date(...) by a string in the format found in the property [DateTimeFormat].
            var matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
            var regex = new Regex(@"\/Date\((-?\d+)\)\/");
            json = regex.Replace(json, matchEvaluator);

            result.Append(json);
        }
        return result.ToString();
    }

    /// <summary>
    /// Converts a JSON string to a object array.
    /// </summary>
    /// <param name="input">The input.</param>
    /// <exception cref="System.ArgumentException">Thrown when input is null.</exception>
    /// <returns></returns>
    public object[] FromJson(string input)
    {
        if (input == null) { throw new ArgumentNullException("input"); }
        var serializer = new JavaScriptSerializer();
        object[] result = serializer.Deserialize(input, typeof(object[])) as object[];

        return result;
    }

    /// <summary>
    /// Replace JSON dates, like "\/Date(1330740183000)\/" to a string in the format found in the property [DateTimeFormat].
    /// </summary>
    /// <param name="match">When null, throws exception</param>
    /// <exception cref="ArgumentNullException">Throws ArgumentNullException, when property [DateTimeFormat] is null, empty or contains only white spaces.</exception>
    /// <returns>A string in the format found in the property [DateTimeFormat]</returns>
    public string ConvertJsonDateToDateString(Match match)
    {
        if (match == null) { throw new ArgumentNullException("match"); }
        if (string.IsNullOrWhiteSpace(DateTimeFormat)) { throw new ArgumentNullException("DateTimeFormat"); }

        string result = string.Empty;
        DateTime dt = new DateTime(1970, 1, 1); // Epoch date, used by the JavaScriptSerializer to represent starting point of datetime in JSON.
        dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
        dt = dt.ToLocalTime();
        result = dt.ToString(DateTimeFormat);
        return result;
    }
}

 

Just an other tip on JSON, if you want to de-serialize a JSON string containing a object with field names, you can use:

string json = @"{Id:1,Barcode:""WWW12312345678""}";
var serializer = new JavaScriptSerializer();
var dict = serializer.Deserialize<Dictionary<string, string>>(json);
Console.WriteLine(dict["Barcode"]);

One Comment

  1. Hi Roel,

    JSON.NET has this build in. No datetime hacks or regex. Check out the Nuget in VS, since JSON.NET is the best thing since sliced bread. 🙂

    Check out the features:
    http://json.codeplex.com/

    DataSets, Tables and Rows:
    http://www.west-wind.com/weblog/posts/2008/Sep/03/DataTable-JSON-Serialization-in-JSONNET-and-JavaScriptSerializer

    Basically, if you’re doing anything with JSON in C#, use JSON.NET. It even has it’s own LINQ provider.

    Gerben Rampaart

Leave a Reply

Your email address will not be published. Required fields are marked *

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