Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON serialization of optional values with FsPickler

Is it possible to serialize optional values in F# using FsPickler such that:

  • when the value is Some(), the value contained is serialized
  • and when it is None, it does not get serialized at all?

With the following example code:

type Person = { name: string; age: int option }

let data = [
  { name = "Helena"; age = Some(24) };
  { name = "Peter"; age = None }
] 

let jsonSerializer = FsPickler.CreateJsonSerializer(true, true)
let streamWriter = new StreamWriter(@"C:\output.json")
let out = jsonSerializer.SerializeSequence(streamWriter, data)

the output.json file contains the following JSON:

[
  {
    "name": "Helena",
    "age": {
      "Some": 24
    }
  },
  {
    "name": "Peter",
    "age": null
  }
]

But I would like the contents of JSON file to look like this instead:

[
  {
    "name": "Helena",
    "age": 24
  },
  {
    "name": "Peter"
  }
]

I am using FsPickler.Json v3.2.0 and Newtonsoft.Json v9.0.1.

UPDATE (January 11, 2017): Using the script in the gist linked by Stuart in the answer below, I got it working like this:

let obj = { name = "Peter"; age = None }
let stringWriter = new StringWriter()
let jsonSerializer = new JsonSerializer()
jsonSerializer.Converters.Add(new IdiomaticDuConverter())
jsonSerializer.NullValueHandling <- NullValueHandling.Ignore
jsonSerializer.Serialize(stringWriter, obj)
like image 847
Carlos Rodriguez Avatar asked Jan 10 '17 21:01

Carlos Rodriguez


2 Answers

Using Newtonsoft.Json you can use the gist here (credit: Isaac Abraham) to give you the behaviour you are after.

It's funny, just moments before you posted this, I was looking to see if the same thing exists within FsPickler.Json, but came to no conclusions. You could use TypeShape which is used in FsPickler to make the gist cleaner, but not sure if FsPickler.Json can do this for you out of the box.

like image 100
Stuart Avatar answered Sep 28 '22 08:09

Stuart


I'm the author FsPickler, so thought I'd repost a response I gave in a similar issue.

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.

like image 35
eirik Avatar answered Sep 28 '22 09:09

eirik