Struct JSON serializer/deserializer http://deavmi.assigned.network/projects/jstruct
Go to file
Tristan B. Velloza Kildaire 169a0bb48f
Merge pull request #3 from ashcyber/patch-1
Update exceptions.d
2023-02-01 13:34:04 +02:00
branding Added branding 2023-01-09 10:33:01 +02:00
source/jstruct Update exceptions.d 2023-01-28 16:48:10 -05:00
.gitignore Updated .gitignore 2023-01-09 10:33:14 +02:00
LICENSE Added license file 2023-01-09 10:34:49 +02:00
README.md Initial release 2023-01-09 10:59:46 +02:00
dub.json Initial commit 2023-01-09 10:32:53 +02:00

README.md

jstruct

Struct JSON serializer/deserializer


Usage

Serialization

Below we define a struct called Person:

struct Person
{
    public string firstname, lastname;
    public int age;
    public string[] list;
    public JSONValue extraJSON;
}

Let's create a instance and set some values before we continue:

Person p1;
p1.firstname  = "Tristan";
p1.lastname = "Kildaire";
p1.age = 23;
p1.list = ["1", "2", "3"];
p1.extraJSON = parseJSON(`{"item":1, "items":[1,2,3]}`);

Now, we make a call to serializeRecord as follows:

JSONValue serialized = serializeRecord(p1);

This returns the following JSON:

{
    "age": 23,
    "extraJSON": {
        "item": 1,
        "items": [
            1,
            2,
            3
        ]
    },
    "firstname": "Tristan",
    "lastname": "Kildaire",
    "list": "[\"1\", \"2\", \"3\"]"
}

Deserialization

Deserialization works by having your predefined struct type and then looking up those field names in the provided JSON. Therefore for this we will be using the following struct type:

struct Person
{
    public string firstname, lastname;
    public int age;
    public bool isMale;
    public JSONValue obj;
}

Now, let's say we were given the following JSON:

{
    "firstname" : "Tristan",
    "lastname": "Kildaire",
    "age": 23,
    "obj" : {"bruh":1},
    "isMale": true,
}

We can then deserialize the JSON to our type Person, with the fromJSON method:

// Define our JSON
JSONValue json = parseJSON(`{
"firstname" : "Tristan",
"lastname": "Kildaire",
"age": 23,
"obj" : {"bruh":1},
"isMale": true,
"list": [1,2,3]
}
`);

// Deserialize
Person person = fromJSON!(Person)(json);

And we can confirm this with:

writeln(person):

Which will output:

Person("Tristan", "Kildaire", 23, true, {"bruh":1})

Installing

In order to use jstruct in your project simply run:

dub add jstruct

And then in your D program import as follows:

import jstruct;

Help wanted

There are some outstanding issues I want to be able to fix/have implemented, namely:

  • Support for array serialization/deserialization - see issue #1
  • Support for custom types serialization/deserialization (think enums for example) - see issue #2