iridium-json

Iridium-Json is a a lightweight and ultra-fast implementation of a basic JSON serializer/deserializer. It also allows updating JSON objects at runtime.

Parsing / Deserializing

JSON documents can be deserialized to a native JsonObject object or to a custom class:

Example JSON:

{
  "storeName": "Costco",
  "products": [
     {
         "id": 1,
         "name": "Apple iPhone",
         "price": 499
     },
     {
         "id": 2,
         "name": "Google Pixel"
     },
  ] 
}
JsonObject json = JsonParser.Parse(jsonText);

string storeName = json["storeName"];

foreach (var jsonProduct in json["products"])
{
   int id = jsonProduct["id"];            // implicit conversion to int
   string name = jsonProduct["name"];     // implicit conversion to string
   decimal? price = jsonProduct["price"]; // implicit conversion to decimal?

   // price will be null if the field is not present in JSON
}

Calling ["..."] on a json object will never throw an exception, even if the key does not exist or it is enumerated when it's not an array type. In fact, the index operator ["..."] returns a new JsonObject so indexers can be chained. If a key doesn't exist, a JsonObject will be returned that has IsUndefined set to true. When enumerated, it will will return an empty enumeration:

// Using the JSON as shown above

// The following line will not crash. The enumeration will be empty
foreach (var jItem in json["badProducts"])
{
}

// Check if "badProducts" exists and is an array:

if (json["badProducts"].IsUndefined)
{
  // there's no such key
}

if (json["badProducts"].IsArray)
{
  // make sure "badProducts" exists and is an array
}

Deserializing to a custom class

public class Product
{
   public int id;
   public string name;
   public decimal? price;
}
public class Store
{
   public string storeName;

   public Product[] products;
}

////

Store store = JsonParser.Parse<Store>(jsonText);

Serializing objects

// create anonymous object
var obj = new
{
   storeName = "Costco",
   products = new object[] 
   {
      new { id = 1, name = "Apple iPhone", price = 499.0 },
      new { id = 2, name = "Google Pixel" }
   }
};

string json = JsonSerializer.ToJson(obj);