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 JSONValue

JSONValue to deserialize.

options JsonizeOptions

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.

assert(JSONValue(1).fromJSON!int      == 1);
assert(JSONValue(2u).fromJSON!uint    == 2u);
assert(JSONValue(3.0).fromJSON!double == 3.0);

// fromJSON accepts numeric strings when a numeric conversion is requested
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.

import jsonizer.jsonize;
static struct MyStruct {
  mixin JsonizeMe;

  @jsonize int i;
  @jsonize string s;
  float f;
}

auto json = `{ "i": 5, "s": "tally-ho!" }`.parseJSON;
auto val = json.fromJSON!MyStruct;
assert(val.i == 5);
assert(val.s == "tally-ho!");

Meta