DavidArno / SuccincT

Discriminated unions, pattern matching and partial applications for C#
MIT License
267 stars 15 forks source link

Json Serializer for Union Type #17

Closed rubiktubik closed 7 years ago

rubiktubik commented 7 years ago

Hello i'am using your great library but now i'am coming to a problem when i need to serialize my objects. My objects use the the Union<T0,T1> type. Is there a example how to serialize with JSON.Net for example?

Michael

DavidArno commented 7 years ago

Oh, that's an interesting one. Bit embarrassing to admit, but it has never occurred to me that someone might want to serialise a union!

So the honest answer is that Succinc<T> has no support currently, but it's certainly something that can be added.

rubiktubik commented 7 years ago

Too bad :-( Then in the moment i need a way around it :-)

DavidArno commented 7 years ago

@rubiktubik,

Quick update on this.

I don't want to make Succinc<T> itself dependent on JSON.Net, therefore I'll create a new SuccincT.JSON nuget package, which will include Succinc<T> itself and support for serializing union types to JSON. That serialization will likely be achieved via custom JsonConverter and ContractResolver classes, rather than by annotating the types with JSON.Net specific attributes.

This'll mean you'd have to do something like:

string json = JsonConvert.SerializeObject(
    dataIncludingUnions,
    Formatting.Indented,
    new JsonSerializerSettings { ContractResolver = new SuccinctContractResolver() });

ie, whenever you need to serialize/deserialize any JSON that would include a union, you'd have to specify the custom ContractResolver class. Would that work for you?

rubiktubik commented 7 years ago

Yes!, that would be perfectly work! I've seen similar approaches at other libraries.

Thank you for your effort.

DavidArno commented 7 years ago

Tasks required to complete this work:

DavidArno commented 7 years ago

Version 2.2.0 of SuccincT.JSON is now available on nuget, which supplies JSON serialization support for Succinc\<T> types.

This is the first release, but the version number has been set to coincide with the compatible release of Succinc\<T> itself.

Please see the JSON Serialization page for details of its use.