Created
January 6, 2013 00:44
-
-
Save eulerfx/4464543 to your computer and use it in GitHub Desktop.
A Json.NET converter for the F# list type.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System | |
open System.Collections.Generic | |
open Microsoft.FSharp.Reflection | |
open Newtonsoft.Json | |
open Newtonsoft.Json.Converters | |
type ListConverter() = | |
inherit JsonConverter() | |
override x.CanConvert(t:Type) = | |
t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<list<_>> | |
override x.WriteJson(writer, value, serializer) = | |
let list = value :?> System.Collections.IEnumerable |> Seq.cast | |
serializer.Serialize(writer, list) | |
override x.ReadJson(reader, t, _, serializer) = | |
let itemType = t.GetGenericArguments().[0] | |
let collectionType = typedefof<IEnumerable<_>>.MakeGenericType(itemType) | |
let collection = serializer.Deserialize(reader, collectionType) :?> IEnumerable<_> | |
let listType = typedefof<list<_>>.MakeGenericType(itemType) | |
let cases = FSharpType.GetUnionCases(listType) | |
let rec make = function | |
| [] -> FSharpValue.MakeUnion(cases.[0], [||]) | |
| head::tail -> FSharpValue.MakeUnion(cases.[1], [| head; (make tail); |]) | |
make (collection |> Seq.toList) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment