painlessjson.painlessjson



JSONValue defaultToJSON(T, SerializationOptions options = defaultSerializatonOptions)(in T t);
Convert any type to JSON
Can be overridden by _toJSON

JSONValue toJSON(T, SerializationOptions options = defaultSerializatonOptions)(in T t);
Template function that converts any object to JSON

Examples:
Converting common types
assertEqual(5.toJSON!int, JSONValue(5));
assert(4.toJSON != JSONValue(5)); //TODO: Wait for DUnit to implement assertNotEqual
assertEqual(5.4.toJSON, JSONValue(5.4));
assertEqual(toJSON("test"), JSONValue("test"));
assertEqual(toJSON(JSONValue("test")), JSONValue("test"));


Examples:
Converting InputRanges
assertEqual([1, 2].toJSON.toString, "[1,2]");


Examples:
User structs
Point p;
assertEqual(toJSON(p).toString, q{{"x":0,"y":1}});


Examples:
Array of structs
Point[] ps = [Point(-1, 1), Point(2, 3)];
assertEqual(toJSON(ps).toString, q{[{"x":-1,"y":1},{"x":2,"y":3}]});


Examples:
User class
PointC p = new PointC(1, -2);
assertEqual(toJSON(p).toString, q{{"x":1,"y":-2}});


Examples:
User class with private fields
PointPrivate p = new PointPrivate(-1, 2);
assertEqual(toJSON(p).toString, q{{"x":-1,"y":2}});
auto pnt = p.toJSON.fromJSON!PointPrivate;
assertEqual(p.x, -1);
assertEqual(p.y, 2);


Examples:
User class with defaultToJSON
PointDefaultFromJSON p = new PointDefaultFromJSON(-1, 2);
assertEqual(toJSON(p).toString, q{{"_x":-1,"y":2}});
auto pnt = p.toJSON.fromJSON!PointDefaultFromJSON;
assertEqual(p.x, -1);
assertEqual(p.y, 2);


Examples:
User class with private fields and @property
auto p = PointPrivateProperty(-1, 2);
assertEqual(toJSON(p).toString, q{{"x":-1,"y":2,"z":1}});


Examples:
User class with SerializedName annotation
auto p = PointSerializationName(-1, 2);
assertEqual(toJSON(p)["xOut"].floating, -1);
assertEqual(toJSON(p)["yOut"].floating, 2);


Examples:
User class with SerializeIgnore annotations
auto p = PointSerializationIgnore(-1, 5, 4);
assertEqual(toJSON(p).toString, q{{"z":5}});


Examples:
Array of classes
PointC[] ps = [new PointC(-1, 1), new PointC(2, 3)];
assertEqual(toJSON(ps).toString, q{[{"x":-1,"y":1},{"x":2,"y":3}]});


Examples:
Associative array
string[int] aa = [0 : "a", 1 : "b"];
assert(aa.toJSON.toString == q{{"0":"a","1":"b"}});
Point[int] aaStruct = [0 : Point(-1, 1), 1 : Point(2, 0)];
assertEqual(aaStruct.toJSON.toString, q{{"0":{"x":-1,"y":1},"1":{"x":2,"y":0}}});
assertEqual(["key": "value"].toJSON.toString, q{{"key":"value"}});


Examples:
Associative array containing struct
assertEqual(["test": SimpleStruct("test2")].toJSON().toString, q{{"test":{"str":"test2"}}});


Examples:
Associative array with struct key
assertEqual([SimpleStruct("key"): "value", SimpleStruct("key2"): "value2"].toJSON().toString, q{{"{\"str\":\"key\"}":"value","{\"str\":\"key2\"}":"value2"}});


Examples:
struct with inner struct and AA
auto testStruct = StructWithStructAndAA(["key1": "value1"], ["key2": StructWithStructAndAA.Inner("value2")]);
auto converted = testStruct.toJSON();
assertEqual(converted["stringToInner"].toString, q{{"key2":{"str":"value2"}}});
assertEqual(converted["stringToString"].toString, q{{"key1":"value1"}});


Examples:
Unnamed tuples
Tuple!(int, int) point;
point[0] = 5;
point[1] = 6;
assertEqual(toJSON(point).toString, q{{"_0":5,"_1":6}});


Examples:
Named tuples
Tuple!(int, "x", int, "y") point;
point.x = 5;
point.y = 6;
assertEqual(point, fromJSON!(Tuple!(int, "x", int, "y"))(parseJSON(q{{"x":5,"y":6}})));


Examples:
Convert camel case to underscore automatically
CamelCaseConversion value;
value.wasCamelCase = 5;
value.was_underscore = 7;

auto valueAsJSON = value.toJSON!(CamelCaseConversion,SerializationOptions(false, true));

assertEqual(valueAsJSON["was_camel_case"].integer, 5); 
assertEqual(valueAsJSON["was_underscore"].integer, 7);


Examples:
Overloaded toJSON
class A
{
    double x = 0;
    double y = 1;
    JSONValue toJSON()
    {
        JSONValue[string] json;
        json["x"] = x;
        return JSONValue(json);
    }

}

auto a = new A;
assertEqual(a.toJSON.toString, q{{"x":0}});

class B
{
    double x = 0;
    double y = 1;
}

// Both templates will now work for B, so this is ambiguous in D.
// Under dmd it looks like the toJSON!T that is loaded first is the one used
JSONValue toJSON(T : B)(T b)
{
    JSONValue[string] json;
    json["x"] = b.x;
    return JSONValue(json);
}

auto b = new B;
assertEqual(b.toJSON.toString, q{{"x":0,"y":1}});

class Z
{
    double x = 0;
    double y = 1;
    // Adding an extra value
    JSONValue toJSON()
    {
        JSONValue[string] json = painlessjson.toJSON!Z(this).object;
        json["add"] = "bla".toJSON;
        return JSONValue(json);
    }

}

auto z = new Z;
assertEqual(z.toJSON["x"].floating, 0);
assertEqual(z.toJSON["y"].floating, 1);
assertEqual(z.toJSON["add"].str, "bla");


T defaultFromJSON(T, SerializationOptions options = defaultSerializatonOptions)(in JSONValue json);
Convert to given type from JSON.
Can be overridden by _fromJSON.

T fromJSON(T, SerializationOptions options = defaultSerializatonOptions)(in JSONValue json);
Convert from JSONValue to any other type

Examples:
Converting common types
assertEqual(fromJSON!int(JSONValue(1)), 1);
assertEqual(fromJSON!double(JSONValue(1.0)), 1);
assertEqual(fromJSON!double(JSONValue(1.3)), 1.3);
assertEqual(fromJSON!string(JSONValue("str")), "str");
assertEqual(fromJSON!bool(JSONValue(true)), true);
assertEqual(fromJSON!bool(JSONValue(false)), false);
assertEqual(fromJSON!JSONValue(JSONValue(true)), JSONValue(true));


Examples:
Converting arrays
assertEqual(fromJSON!(int[])(toJSON([1, 2])), [1, 2]);
assertEqual(fromJSON!(Point[])(parseJSON(q{[{"x":-1,"y":2},{"x":3,"y":4}]})), [Point(-1,2),Point(3,4)]);


Examples:
Array as member of other class
// Types need to be defined in different module, otherwise 
// type is not known at compile time
import painlessjson.unittesttypes_local_import;

string jsonString = q{[ {"duration": "10"} ]};
Route[] routes = parseJSON(jsonString).fromJSON!(Route[]);
assertEqual(routes.length, 1);

jsonString = q{{"routes":[ {"duration": "10"} ] }};
JourneyPlan jp;
jp = parseJSON(jsonString).fromJSON!JourneyPlan;
assertEqual(jp.routes.length, 1);


Examples:
Associative arrays
string[int] aaInt = [0 : "a", 1 : "b"];
assertEqual(aaInt, fromJSON!(string[int])(parseJSON(q{{"0" : "a", "1": "b"}})));

string[string] aaString = ["hello" : "world", "json" : "painless"];
assertEqual(aaString, fromJSON!(string[string])(parseJSON(q{{"hello" : "world", "json" : "painless"}})));


Examples:
Associative array containing struct
auto parsed = fromJSON!(SimpleStruct[string])(parseJSON(q{{"key": {"str": "value"}}}));
assertEqual(parsed , ["key": SimpleStruct("value")]);


Examples:
Associative array with struct key
JSONValue value = parseJSON(q{{"{\"str\":\"key\"}":"value", "{\"str\":\"key2\"}":"value2"}});
auto parsed = fromJSON!(string[SimpleStruct])(value);
assertEqual(
    parsed
    , [SimpleStruct("key"): "value", SimpleStruct("key2"): "value2"]);


Examples:
struct with inner struct and AA
auto testStruct = StructWithStructAndAA(["key1": "value1"], ["key2": StructWithStructAndAA.Inner("value2")]);
auto testJSON = parseJSON(q{{"stringToInner":{"key2":{"str":"value2"}},"stringToString":{"key1":"value1"}}});
assertEqual(fromJSON!StructWithStructAndAA(testJSON), testStruct);


Examples:
Error reporting from inner objects
import std.exception : collectExceptionMsg;
import std.algorithm : canFind;
void throwFunc() {
    fromJSON!(string[SimpleStruct])(parseJSON(q{{"{\"str\": \"key1\"}": "value", "key2":"value2"}}));
}
auto errorMessage = collectExceptionMsg(throwFunc());
assert(errorMessage.canFind("key2"));
assert(errorMessage.canFind("string[SimpleStruct]"));
assert(!errorMessage.canFind("key1"));


Examples:
Structs from JSON
auto p = fromJSON!Point(parseJSON(q{{"x":-1,"y":2}}));
assertEqual(p.x, -1);
assertEqual(p.y, 2);
p = fromJSON!Point(parseJSON(q{{"x":2}}));
assertEqual(p.x, 2);
assertEqual(p.y, 1);
p = fromJSON!Point(parseJSON(q{{"y":3}}));
assertEqual(p.x, 0);
assertEqual(p.y, 3);
p = fromJSON!Point(parseJSON(q{{"x":-1,"y":2,"z":3}}));
assertEqual(p.x, -1);
assertEqual(p.y, 2);


Examples:
Class from JSON
auto p = fromJSON!PointC(parseJSON(q{{"x":-1,"y":2}}));
assertEqual(p.x, -1);
assertEqual(p.y, 2);


Examples:
Convert class from JSON using "fromJSON"
auto p = fromJSON!PointPrivate(parseJSON(q{{"x":-1,"y":2}}));
assertEqual(p.x, -1);
assertEqual(p.y, 2);


Examples:
Convert struct from JSON using properties
auto p = fromJSON!PointPrivateProperty(parseJSON(q{{"x":-1,"y":2,"z":3}}));
assertEqual(p.x, -1);
assertEqual(p.y, 2);


Examples:
User class with SerializedName annotation
auto p = fromJSON!PointSerializationName(parseJSON(q{{"xOut":-1,"yOut":2}}));
assertEqual(p.x, 2);
assertEqual(p.y, -1);


Examples:
User class with SerializeIgnore annotations
auto p = fromJSON!PointSerializationIgnore(parseJSON(q{{"z":15}}));
assertEqual(p.x, 0);
assertEqual(p.y, 1);
assertEqual(p.z, 15);


Examples:
Unnamed tuples
Tuple!(int, int) point;
point[0] = 5;
point[1] = 6;
assertEqual(point, fromJSON!(Tuple!(int, int))(parseJSON(q{{"_0":5,"_1":6}})));


Examples:
No default constructor
auto p = fromJSON!PointUseConstructor(parseJSON(q{{"x":2, "y":5}}));
assertEqual(p.x, 2);
assertEqual(p.y, 5);


Examples:
Multiple constructors and all JSON-values are there
auto person = fromJSON!IdAndName(parseJSON(q{{"id":34, "name": "Jason Pain"}}));
assertEqual(person.id, 34);
assertEqual(person.name, "Jason Pain");


Examples:
Multiple constructors and some JSON-values are missing
auto person = fromJSON!IdAndName(parseJSON(q{{"id":34}}));
assertEqual(person.id, 34);
assertEqual(person.name, "Undefined");


Examples:
Accept underscore and convert it to camelCase automatically
auto value = fromJSON!CamelCaseConversion(parseJSON(q{{"was_camel_case":8,"was_underscore":9}}));
assertEqual(value.wasCamelCase, 8);
assertEqual(value.was_underscore, 9);



Page generated by Ddoc.