int | missing | absent

Steven Schveighoffer schveiguy at gmail.com
Wed Jun 22 01:09:22 UTC 2022


On 6/2/22 9:24 AM, bauss wrote:
> 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;
> }
> ```

There are 3 situations:

1. field in json and struct. Obvious result.
2. field in json but not in struct.
3. field in struct but not in json.

In jsoniopipe, I handle 2 by requiring a UDA on the struct to ignore the 
members: 
https://github.com/schveiguy/jsoniopipe/blob/4fa5350ed97786e34612a755f7e857544c6f9512/source/iopipe/json/serialize.d#L50-L55

Or, you can provide a `JSONValue` member, which will contain all 
unexpected members, that you can attribute with `@extras`: 
https://github.com/schveiguy/jsoniopipe/blob/4fa5350ed97786e34612a755f7e857544c6f9512/source/iopipe/json/serialize.d#L38-L43

I handle 3 by requiring a UDA on the field: 
https://github.com/schveiguy/jsoniopipe/blob/4fa5350ed97786e34612a755f7e857544c6f9512/source/iopipe/json/serialize.d#L26-L30

Otherwise it's an error.

I feel it's too loose to make a best effort, and leave the rest up to 
initial values, or just ignore possibly important information during 
parsing.

-Steve


More information about the Digitalmars-d-learn mailing list