fromJSON

Deserialize json into a value of type T.

Parameters

T

Target type. can be any primitive/builtin D type, or any user-defined type using the JsonizeMe mixin.

json
Type: JSONValue

JSONValue to deserialize.

options

configures the deserialization behavior.

Examples

Extract booleans from json values.

assert(JSONValue(false).fromJSON!bool == false);
assert(JSONValue(true).fromJSON!bool == true);

Extract a string from a json string.

assert(JSONValue("asdf").fromJSON!string == "asdf");

Extract various numeric types.

1 assert(JSONValue(1).fromJSON!int      == 1);
2 assert(JSONValue(2u).fromJSON!uint    == 2u);
3 assert(JSONValue(3.0).fromJSON!double == 3.0);
4 
5 // fromJSON accepts numeric strings when a numeric conversion is requested
6 assert(JSONValue("4").fromJSON!long   == 4L);

Convert a json string into an enum value.

enum Category { one, two }
assert(JSONValue("one").fromJSON!Category == Category.one);

Convert a json array into an array.

auto a = [ 1, 2, 3 ];
assert(JSONValue(a).fromJSON!(int[]) == a);

Convert a json object to an associative array.

auto aa = ["a": 1, "b": 2];
assert(JSONValue(aa).fromJSON!(int[string]) == aa);

Convert a json object to a user-defined type. See the docs for JsonizeMe for more detailed examples.

1 import jsonizer.jsonize;
2 static struct MyStruct {
3   mixin JsonizeMe;
4 
5   @jsonize int i;
6   @jsonize string s;
7   float f;
8 }
9 
10 auto json = `{ "i": 5, "s": "tally-ho!" }`.parseJSON;
11 auto val = json.fromJSON!MyStruct;
12 assert(val.i == 5);
13 assert(val.s == "tally-ho!");

Meta