xyncro / chiron

JSON for F#
https://xyncro.tech/chiron
MIT License
173 stars 41 forks source link

Added serializeWith method #63

Closed colinbull closed 8 years ago

colinbull commented 8 years ago

I have added a convenience method serializeWith which allows you to delegate to a function. An example might be truncating the time component of a DateTime .

 Json.serializeWith (fun (x:DateTime) -> Json.Optic.set Json.String_ (x.ToString("yyyy-MM-dd"))) (DateTime (2015, 2, 20, 14, 36, 21, DateTimeKind.Utc)) =! String "2015-02-20" 

this is also useful when you cannot enhance a type with the ToJson method because you may not know the closed form of the type. For example Result<'a, Error> in this case I can't create an extension method as the F# compiler doesn't support it, so this PR lets me do something like,

 let inline serializeResult (r:Result<'a, Error>) =  
      match r with
      | Success v -> Json.write "success" v
      | Failure f -> Json.write "failure" f

 Json.serializeWith serializeResult r

I'm only playing with this seriously for the first time but I couldn't see any obvious way of doing what I wanted to achieve. Open to suggestions if there is a way to do this.

kolektiv commented 8 years ago

This makes sense actually, as at the moment there's no way of serializing an unsupported top level type. We have writeWith and readWith for when an unsupportable type is part of a larger scope, but this does make perfect sense for your case (and I'm sure you won't be unique).

I'll get this merged in later on tonight and a new package pushed out.

colinbull commented 8 years ago

Nice! Thanks.

kolektiv commented 8 years ago

Merged in - look for 6.1.0 appearing shortly...