Wiki

Clone wiki

Manatee.Json / Usage

USAGE

JSON constructs can be created directly through the use of the implicit cast operators:

JsonValue jsonBool = false;
JsonValue jsonNum = 42;
JsonValue jsonString = "aString";
JsonValue jsonObject = new JsonObject{{"aKey", 42}};
JsonValue jsonArray = new JsonArray{4, true, "aValue"};

The above code creates five JsonValue instances. To access these values, use these properties:

jsonBool.Boolean
jsonNum.Number
jsonString.String
jsonObject.Object
jsonArray.Array

If a get accessor is used that does not correspond with the JsonValue’s type, an exception is thrown. The default constructor for JsonValue creates a Null value.

These declarations can be combined in the same way as when declaring any other object. For example, a moderately complex JsonObject can be built as follows:

var json = new JsonObject
    {
        {"boolean", true},
        {"number", 42},
        {"string", "a string"},
        {"null", JsonValue.Null},
        {"array", new JsonArray {6.7, true, "a value"}},
        {"object", new JsonObject
            {
                {"aKey", 42},
                {"anotherKey", false}
            }
        }
    };

The object’s structure, and ultimately its output, is quite apparent directly from the code that created it.

Since JsonObject and JsonArray are implemented as strongly typed collections, all of the underlying operations (e.g. Add(), AddRange(), etc.) are accessible, including LINQ. As such, the following statements are valid:

json.Add("newItem", "a new string");
var onlyStrings = json.Select(jkv => jkv.Value.Type == JsonValueType.String).ToJson();

Here, the ToJson() method is an extension method on the IEnumerable<KeyValuePair<string, JsonValue>> type returned by the LINQ Select() method. It returns a JsonObject. There is also a correlating ToJson() method for the IEnumerable<JsonValue> which returns a JsonArray.

As you can see, creating these constructs is quite easy and very readable. As is expected, calling json.ToString() yields:

{"boolean":true,"number":42,"string":"a string","null":null,"array":[6.7,true,"a value"],"object",{"aKey":42,"anotherKey":false}}

Furthermore, feeding this output back into the JsonObject constructor yields the original structure (although using new instances).

ERROR HANDLING

While parsing JSON data (through either the JsonObject constructor or JsonValue.Parse()), errors may occur. These errors will be reported by throwing a JsonSyntaxException. This exception exposes a Path property which contains a path to the error in JSONPath syntax. The messaging has been designed to direct the user directly to the error.

Home | Architecture | Usage | Serialization | Schema | JSONPath | XML Conversion | Support

Updated