serde-ml / serde

Serialization framework for OCaml
MIT License
174 stars 11 forks source link

Deserialize optional values as Option #4

Closed pjlast closed 1 year ago

pjlast commented 1 year ago

Adds support for optional value deserialization.

When deserializing an object, if a field is missing and that field is defined as an option, it is deserialized to None . Otherwise it is deserialized to Some val

This works for the primitive types as well as more complex types, as shown in the added unit tests.

Given the following type:

type name = {
  first : string;
  last : string option;
}
[@@deriving deserializer]

deserializing the following json:

{ "first": "Petri" }

will result in an object

{ first = "Petri", last = None}
pjlast commented 1 year ago

This is also 100% from a JSON perspective

I have no idea if this same concept applies to other formats. If not, it would have to take a different approach

pjlast commented 1 year ago

This also doesn't handle cases where a value is explicity set as null, that would require changes to specific deserializers.

having to decide what to do with something that's explicitly set as null is always a bit weird anyways

pjlast commented 1 year ago

I think perhaps optionals should be serializer dependent, so that serializers that don't support it can return Error.unimplemented. But it makes it somewhat trickier to implement

pjlast commented 1 year ago

This is the other approach I tried: https://github.com/pjlast/serde.ml/pull/3/files

But I simply cannot get this to work with more complex optional fields. But at least it works with nulls

I'm open to suggestions, but otherwise this current solution is perhaps the way to go for now. It at least gives me all the functionality I want for JSON deserialization 😄

(optional serialization is a whole nother beast)

pjlast commented 1 year ago

Closing in favour of https://github.com/leostera/serde.ml/pull/5 , which handles both null values as well as missing values