jstruct/docs/deserialization.md

73 lines
1.4 KiB
Markdown
Raw Normal View History

2023-01-09 10:03:16 +00:00
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:
```d
struct Person
{
public string firstname, lastname;
public int age;
public bool isMale;
public JSONValue obj;
2023-06-24 13:54:00 +01:00
public int[] list;
public bool[] list2;
public float[] list3;
public double[] list4;
public string[] list5;
2023-06-28 15:52:32 +01:00
public EnumType animal;
2023-01-09 10:03:16 +00:00
}
```
Now, let's say we were given the following JSON:
```json
{
"firstname" : "Tristan",
"lastname": "Kildaire",
"age": 23,
"obj" : {"bruh":1},
"isMale": true,
2023-06-24 13:54:00 +01:00
"list": [1,2,3],
"list2": [true, false],
"list3": [1.5, 1.4],
"list4": [1.5, 1.4],
2023-06-28 15:52:32 +01:00
"list5": ["baba", "booey"],
"animal": "CAT"
2023-01-09 10:03:16 +00:00
}
```
We can then deserialize the JSON to our type `Person`, with the `fromJSON` method:
```d
// Define our JSON
JSONValue json = parseJSON(`{
"firstname" : "Tristan",
"lastname": "Kildaire",
"age": 23,
"obj" : {"bruh":1},
"isMale": true,
2023-06-24 13:54:00 +01:00
"list": [1,2,3],
"list2": [true, false],
"list3": [1.5, 1.4],
"list4": [1.5, 1.4],
2023-06-28 15:52:32 +01:00
"list5": ["baba", "booey"],
"animal": "CAT"
2023-01-09 10:03:16 +00:00
}
`);
// Deserialize
Person person = fromJSON!(Person)(json);
```
And we can confirm this with:
```d
writeln(person):
```
Which will output:
```
2023-06-28 15:52:32 +01:00
Person("Tristan", "Kildaire", 23, true, {"bruh":1}, [1, 2, 3], [true, false], [1.5, 1.4], [1.5, 1.4], ["baba", "booey"], CAT)
2023-01-09 10:03:16 +00:00
```