The OpenD Programming Language

serializeJson

JSON serialization function.

import mir.ser.json;
alias serializeJson = serializeJsonPretty!""

Examples

struct S
{
    string foo;
    uint bar;
}

assert(serializeJson(S("str", 4)) == `{"foo":"str","bar":4}`);
import mir.serde: serdeIgnoreDefault;

static struct Decor
{
    int candles; // 0
    float fluff = float.infinity; // inf 
}

static struct Cake
{
    @serdeIgnoreDefault
    string name = "Chocolate Cake";
    int slices = 8;
    float flavor = 1;
    @serdeIgnoreDefault
    Decor dec = Decor(20); // { 20, inf }
}

assert(Cake("Normal Cake").serializeJson == `{"name":"Normal Cake","slices":8,"flavor":1.0}`);
auto cake = Cake.init;
cake.dec = Decor.init;
assert(cake.serializeJson == `{"slices":8,"flavor":1.0,"dec":{"candles":0,"fluff":"+inf"}}`);
assert(cake.dec.serializeJson == `{"candles":0,"fluff":"+inf"}`);

static struct A
{
    @serdeIgnoreDefault
    string str = "Banana";
    int i = 1;
}
assert(A.init.serializeJson == `{"i":1}`);

static struct S
{
    @serdeIgnoreDefault
    A a;
}
assert(S.init.serializeJson == `{}`);
assert(S(A("Berry")).serializeJson == `{"a":{"str":"Berry","i":1}}`);

static struct D
{
    S s;
}
assert(D.init.serializeJson == `{"s":{}}`);
assert(D(S(A("Berry"))).serializeJson == `{"s":{"a":{"str":"Berry","i":1}}}`);
assert(D(S(A(null, 0))).serializeJson == `{"s":{"a":{"str":"","i":0}}}`);

static struct F
{
    D d;
}
assert(F.init.serializeJson == `{"d":{"s":{}}}`);
import mir.serde: serdeIgnoreIn;

static struct S
{
    @serdeIgnoreIn
    string s;
}
// assert(`{"s":"d"}`.deserializeJson!S.s == null, `{"s":"d"}`.deserializeJson!S.s);
assert(S("d").serializeJson == `{"s":"d"}`);
import mir.deser.json;

static struct S
{
    @serdeIgnoreOut
    string s;
}
assert(`{"s":"d"}`.deserializeJson!S.s == "d");
assert(S("d").serializeJson == `{}`);
import mir.serde: serdeIgnoreOutIf;

static struct S
{
    @serdeIgnoreOutIf!`a < 0`
    int a;
}

assert(serializeJson(S(3)) == `{"a":3}`, serializeJson(S(3)));
assert(serializeJson(S(-3)) == `{}`);
import mir.rc.array;
auto ar = rcarray!int(1, 2, 4);
assert(ar.serializeJson == "[1,2,4]");
import mir.deser.json;
import std.range;
import std.algorithm;
import std.conv;
import mir.test;

static struct S
{
    @serdeTransformIn!"a += 2"
    @serdeTransformOut!(a =>"str".repeat.take(a).joiner("_").to!string)
    int a;
}

auto s = deserializeJson!S(`{"a":3}`);
s.a.should == 5;
assert(serializeJson(s) == `{"a":"str_str_str_str_str"}`);

JSON serialization for custom outputt range.

import mir.format: stringBuf;
auto buffer = stringBuf;
static struct S { int a; }
serializeJson(buffer, S(4));
assert(buffer.data == `{"a":4}`);

Meta