Click here to Skip to main content
15,860,859 members
Articles / Programming Languages / Markdown

fastJSON - Smallest, Fastest Polymorphic JSON Serializer

Rate me:
Please Sign up or sign in to vote.
4.91/5 (412 votes)
23 Jan 2021CPOL37 min read 5.6M   63.7K   984  
In this article I demonstrate why fastJSON is the smallest, fastest polymorphic JSON serializer (with Silverlight4, MonoDroid and .NET core support)
Here we look at: the what and why of JSON, features of this implementation, some of the JSON alternatives that I have personally used, using the code, and performance tests.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;

namespace fastJSON
{
	internal class JSONSerializer
	{
		private readonly StringBuilder _output = new StringBuilder();
		
		public static string ToJSON(object obj)
		{
			return new JSONSerializer().ConvertToJSON(obj);
		}

		internal string ConvertToJSON(object obj)
		{
			WriteValue(obj);

			return _output.ToString();
		}

		private void WriteValue(object obj)
		{
			if (obj == null || obj is System.DBNull)
				_output.Append("null");
			
			else if (obj is sbyte ||
			         obj is byte ||
			         obj is short ||
			         obj is ushort ||
			         obj is int ||
			         obj is uint ||
			         obj is long ||
			         obj is ulong ||
			         obj is decimal ||
			         obj is double ||
			         obj is float)
				_output.Append(Convert.ToString(obj,NumberFormatInfo.InvariantInfo));
			
			else if (obj is bool)
				_output.Append(obj.ToString().ToLower()); // conform to standard
			
			else if (obj is char || obj is Enum || obj is Guid || obj is string)
				WriteString(obj.ToString());
			
			else if (obj is DateTime)
			{
				_output.Append('\"');
				_output.Append(((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss"));// conform to standard
				_output.Append('\"');
			}
			
			else if(obj is DataSet)
				WriteDataset((DataSet)obj);
			
			else if( obj is byte[])
				WriteByteArray((byte[]) obj);
			
			else if (obj is IDictionary)
				WriteDictionary((IDictionary)obj);
			
			else if (obj is Array || obj is IList || obj is ICollection)
				WriteArray((IEnumerable)obj);
			
			else
				WriteObject(obj);
			
		}
		
		private void WriteByteArray(byte[] bytes)
		{
			WriteString(Convert.ToBase64String(bytes));
		}
		
		private void WriteDataset(DataSet ds)
		{
			_output.Append('{');
			WritePair("$schema", ds.GetXmlSchema());
			_output.Append(',');

			foreach (DataTable table in ds.Tables)
			{
				_output.Append('\"');
				_output.Append(table.TableName);
				_output.Append("\":[");

				foreach (DataRow row in table.Rows)
				{
					_output.Append('{');
					foreach (DataColumn column in row.Table.Columns)
					{
						WritePair(column.ColumnName, row[column]);
					}
					_output.Append('}');
				}

				_output.Append(']');
			}
			// end dataset
			_output.Append('}');
		}

		private void WriteObject(object obj)
		{
			_output.Append('{');
			Type  t = obj.GetType();
			WritePair("$type", t.AssemblyQualifiedName);

			List<Getters> g = JSON.Instance.GetGetters(t);
			foreach (Getters p in g)
			{
				_output.Append(',');
				WritePair(p.Name,p.Getter(obj));
			}
			_output.Append('}');
		}
		
		private void WritePair(string name, string value)
		{
			WriteString(name);

			_output.Append(':');
			
			WriteString(value);
		}

		private void WritePair(string name, object value)
		{
			WriteString(name);

			_output.Append(':');

			WriteValue(value);
		}

		private void WriteArray(IEnumerable array)
		{
			_output.Append('[');

			bool pendingSeperator = false;

			foreach (object obj in array)
			{
				if (pendingSeperator)
					_output.Append(',');

				WriteValue(obj);

				pendingSeperator = true;
			}

			_output.Append(']');
		}

		private void WriteDictionary(IDictionary dic)
		{
			_output.Append('[');

			bool pendingSeparator = false;

			foreach (DictionaryEntry entry in dic)
			{
				if (pendingSeparator)
					_output.Append(',');

				_output.Append('{');
				WritePair("k",entry.Key);
				_output.Append(",");
				WritePair("v",entry.Value);
				_output.Append('}');

				pendingSeparator = true;
			}

			_output.Append(']');
		}
		
		private void WriteString(string s)
		{
			_output.Append('\"');

			foreach (char c in s)
			{
				switch (c)
				{
				    case '\t': _output.Append("\\t"); break;
					case '\r': _output.Append("\\r"); break;
					case '\n': _output.Append("\\n"); break;
					case '"' :
					case '\\': _output.Append('\\');  _output.Append(c); break;
					default:
						{
							if (c >= ' ' && c < 128)
								_output.Append(c);
							else
							{
								_output.Append("\\u");
								_output.Append(((int)c).ToString("X4"));
							}
						}
						break;
				}
			}

			_output.Append('\"');
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect -
United Kingdom United Kingdom
Mehdi first started programming when he was 8 on BBC+128k machine in 6512 processor language, after various hardware and software changes he eventually came across .net and c# which he has been using since v1.0.
He is formally educated as a system analyst Industrial engineer, but his programming passion continues.

* Mehdi is the 5th person to get 6 out of 7 Platinum's on Code-Project (13th Jan'12)
* Mehdi is the 3rd person to get 7 out of 7 Platinum's on Code-Project (26th Aug'16)

Comments and Discussions