On Thursday, 2 June 2022 at 08:27:32 UTC, Antonio wrote:
JSON properties can be
- a value
- null
- absent

What's the standard way to define a serialziable/deserializable structs supporting properties of any of this 4 kinds?:

* int
* int | null
* int | absent
* int | null | absent


Whats the best library to manage this JSON requirements? (all the 4 cases)?


Thanks

null and absent should be treated the same in the code, it's only when serializing you should define one or the other, if you need to have null values AND absent values then attributing accordingly is the solution.

Which means deserialization only has value/null and serialization has value/null by default, but can be opt-in to also have absent.

One common mistake I've seen with parsers in D is that fields are often opt-out, instead of opt-in, which means you always have to declare all fields in a json object, but that's a bad implementation. All fields should be optional and only required when attributed.

An example:

```
struct A { int x; }
```

Should be able to be deserialized from this json:

```
{"x":100,"y":200}
```

However a lot of parsers in D do not support that. Instead you must declare the y member as well like:

```
struct A { int x; int y; }
```

Any decent parser should not have that problem.

If a field is required then it should be determined by an attribute like:

```
struct A {
@JsonRequired int x;
@JsonRequired int y;
}
```

If that attribute isn't present then it can be absent during deserialization.

Sorry I got a little off-track, but I felt like pointing these things out are important as well.

Reply via email to