Skip to content

Instantly share code, notes, and snippets.

@eulerfx
Created January 6, 2013 00:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eulerfx/4464543 to your computer and use it in GitHub Desktop.
Save eulerfx/4464543 to your computer and use it in GitHub Desktop.
A Json.NET converter for the F# list type.
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