How to use F # connection types with JSON Servicestack serialization?

I think this is too much what I ask from the framework. But just wondering if it is possible at all. Or what will work for this.

JSON.Net with the new release began to support F # union types. For what this works, means that if I use servicestack.text, then how can I flatten connection types to support serialization.

Here is a sample code for both.

type Shape = | Rectangle of width : float * length : float | Circle of radius : float | Empty [<EntryPoint>] let main argv = // printfn "%A" argv let shape1 = Rectangle(1.3, 10.0) let json = JsonConvert.SerializeObject(shape1) //JSON.net printfn "%A" json // { // "Case": "Rectangle", // "Fields": [ // 1.3, // 10.0 // ] // } let shape2 = JsonConvert.DeserializeObject<Shape>(json) //JSON.Net printfn "%A" (shape2 = shape1) //true let sJson = JsonSerializer.SerializeToString shape1 //SS.Text printfn "%A" sJson let sShape2 = JsonSerializer.DeserializeFromString sJson //SS.Text printfn "%A" (sShape2 = shape1) //false Console.Read() |> ignore 0 // return an integer exit code 

Deserialization using a utility returns false. And also the generated json string is quite complicated compared to JSON.net.

How to achieve proper serialization for Union types?

+7
json f # servicestack c # -to-f # servicestack-text
source share
1 answer

You will have to provide ServiceStack with your own serializer. He would like this using a smaller Shape type for brevity:

 open ServiceStack.Text type Shape = | Circle of float | Empty JsConfig<Shape>.SerializeFn <- Func<_,_> (function | Circle r -> sprintf "C %f" r | Empty -> sprintf "E") JsConfig<Shape>.DeSerializeFn <- Func<_,_> (fun s -> match s.Split [| |] with | [| "C"; r |] -> Circle (float r) | [| "E" |] -> Empty) let shapes = [| Circle 8.0 |] let json = JsonSerializer.SerializeToString(shapes) let shapes1 = JsonSerializer.DeserializeFromString<Shape[]>(json) let is_ok = shapes = shapes1 

This code does not have the right exception throwing in the deserializer: you have to handle match mismatches, and a float can raise a System.FormatException .

+2
source share

All Articles