JSONParser.updateStruct

Push object contents into a struct or class.

The object doesn't have to contain all fields defined in the struct or class.

Fields that share names with D reserved keywords can be suffixed with _, as according to the D style.

The struct or class must have a no argument constructor available.

  1. T updateStruct(T obj, void delegate(ref T, wstring) fallback)
    struct JSONParser
    T
    updateStruct
    (
    T
    )
    (
    T obj
    ,
    void delegate
    (
    ref T
    ,
    wstring
    )
    fallback = null
    )
    if (
    is(T == struct) ||
    is(T == class)
    )
  2. T getStruct(void delegate(ref T, wstring) fallback)

Parameters

T

Type of the struct.

obj T

Instance of the object to modify. Classes are edited in place, structs are not.

fallback void delegate
(
ref T
,
wstring
)

Function to call if a field doesn't exist. Otherwise, it will be ignored.

Return Value

Type: T

1. If T is a struct, a copy of the given object with updated properties. 2. If T is a class, a reference to the given object. (ret is obj)

Throws

JSONException if there's a type mismatch or syntax error.

Examples

struct Example {
    string name;
    int version_;
    string[] contents;
}

auto json = JSONParser(q{
    {
        "name": "rcjson",
        "version": 123,
        "contents": ["json-parser"]
    }
});
const obj = json.getStruct!Example;
assert(obj.name == "rcjson");
assert(obj.version_ == 123);
assert(obj.contents == ["json-parser"]);

Using fallback

struct Table {

    string tableName;

    @JSONExclude
    string[string] attributes;

}

auto json = JSONParser(q{
    {
        "tableName": "Player",
        "id": "PRIMARY KEY INT",
        "name": "VARCHAR(30)",
        "xp": "INT",
        "attributes": "VARCHAR(60)"
    }
});

auto table = json.getStruct!Table((ref Table table, wstring key) {

    import std.conv : to;
    table.attributes[key.to!string] = json.getString.to!string;

});

assert(table.tableName == "Player");
assert(table.attributes["id"] == "PRIMARY KEY INT");
assert(table.attributes["xp"] == "INT");
assert(table.attributes["attributes"] == "VARCHAR(60)");

Meta