JSON serialization of optional values โ€‹โ€‹using FsPickler

Is it possible to serialize optional values โ€‹โ€‹in F # using FsPickler so that:

  • when the value of Some (), the contained value is serialized
  • and when he is absent, is he not serialized at all?

In the following code example:

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 the JSON file to look like this:

 [ { "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 a script in gist related to Stuart, in the answer below I got the following:

 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) 
+5
source share
3 answers

Using Newtonsoft.Json, you can use the gist here (credit: Isaac Abraham) to give you behavioral behavior.

It's funny, just a few minutes before you posted this post, I was looking to see if the same thing exists in FsPickler.Json, but made no conclusions. You can use TypeShape, which is used by FsPickler to make gist clean, but not sure if FsPickler.Json can do this for you out of the box.

+2
source

I am the author of FsPickler, so I thought that I would answer the answer that I gave in a similar issue .

No, managing the form of serialization formats goes beyond the design goals of this library. While you can use sorter combinators to influence what serialized types look like, this will keep you busy for now.

+1
source

With FSharp.Json, the library will work very well:

 open FSharp.Json type Person = { name: string; age: int option } let data = [ { name = "Helena"; age = Some(24) }; { name = "Peter"; age = None } ] let json = Json.serialize data 

This results in the following JSON:

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

Alternatively, the serialized version is configured. Here, how to omit a parameter member that is None, pay attention to config:

 let config = JsonConfig.create(serializeNone=SerializeNone.Omit) let json = Json.serializeEx config data 

Disclosure: I am the author of the FSharp.Json library.

0
source

Source: https://habr.com/ru/post/1262608/


All Articles