mbraceproject / FsPickler

A fast multi-format message serializer for .NET
http://mbraceproject.github.io/FsPickler/
MIT License
323 stars 54 forks source link

Question: How to serialize option type to more idiomatic json? #79

Closed 2moveit closed 7 years ago

2moveit commented 7 years ago

Hi, if I serialze this:

open MBrace.FsPickler.Json
let private jsonSerializer = FsPickler.CreateJsonSerializer(indent = true, omitHeader = true)
let serialize obj = jsonSerializer.PickleToString(obj)

type MyType = {Key: string; Value:string option}
let o1 = {Key="None value test"; Value=None}
let o2 = {Key="Some Value test"; Value=Some "Text"}

serialize o1
serialize o2

The json result is:

{ "Key": "None value test",
  "Value": null }
{ "Key": "Some Value test",
  "Value": { "Some": "Text" }}

Is it somehow possible to change that behavior to always get a result like this in stead of null and a nested value?

{ "Key": "None value test" }
{ "Key": "Some Value test",
  "Value": "Text"}

During my research I found a possible solution on SO but they are using Json.Net directly. I think it should be somehow possible to configure FsPickler so that this result is possible.

eiriktsarpalis commented 7 years ago

No, managing the shape of the serialization formats is beyond the design goals of this library. While you could use pickler combinators to influence how serialized types look like, this will only take you so far.

2moveit commented 7 years ago

Ahh ok, thanks for clarification and the hint with the combinators. I tried it with combinator but so far I was not able to get it to work. It's not really the serialization format that is important to me. If I try to deserialize it e.g. into a C# class it's not that nice with the "Some" key as there is no option type in C#. So it's more interoperability within .NET from my point of view. So it would be really nice to figure it out how to achieve it with combinators.

eiriktsarpalis commented 7 years ago

FsPickler is a serializer for types, so you should always deserialize using the same .NET type.

2moveit commented 7 years ago

OK, thanks