C# JSON Parser

Motivation

I’ve had a go at writing my own JSON parser. Why?

Unity Engine’s mono runtime doesn’t have JIT support on iOS and has a relatively simple garbage collection scheme. It is fiddly with existing parsers to get them up and running in Unity. DLLs in Unity are a pain, especially if they use JIT or the wrong .NET framework version and you also lose source access when debugging.

So my main goal here is to write the simplest JSON parser and writer, in as few lines as possible, whilst minimising memory usage. Speed and performance is less of a concern.

Installation

Simply copy and paste the JSON Parser and/or the JSON Writer

Documentation

A really simple C# JSON parser in ~300 lines

  • Attempts to parse JSON files with minimal GC allocation
  • Nice and simple "[1,2,3]".FromJson<List<int>>() API
  • Classes and structs can be parsed too!

    1
    2
    3
    4
    5
    class Foo
    {
    public int Value;
    }
    "{\"Value\":10}".FromJson<Foo>()
  • Anonymous JSON is parsed into Dictionary<string,object> and List<object>

    1
    2
    var test = "{\"Value\":10}".FromJson<object>();
    int number = ((Dictionary<string,object>)test)["Value"];
  • No JIT Emit support to support AOT compilation on iOS

  • Attempts are made to NOT throw an exception if the JSON is corrupted or invalid: returns null instead.
  • Only public fields and property setters on classes/structs will be written to

Limitations:

  • No JIT Emit support to parse structures quickly
  • Limited to parsing <2GB JSON files (due to int.MaxValue)
  • Parsing of abstract classes or interfaces is NOT supported and will throw an exception.

Example Usage

This example will write a list of ints to a File and read it back again:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.IO;
using System.Collections.Generic;
using TinyJson;
public static class JsonTest
{
public static void Main(string[] args)
{
//Write a file
List<int> values = new List<int> { 1, 2, 3, 4, 5, 6 };
string json = values.ToJson();
File.WriteAllText("test.json", json);
//Read it back
string fileJson = File.ReadAllText("test.json");
List<int> fileValues = fileJson.FromJson<List<int>>();
}
}

Save this as JsonTest.cs then compile and run with mcs JsonTest.cs && mono JsonTest.exe