Created
December 23, 2011 17:30
-
-
Save t0yv0/1514856 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
type Json = | |
| Array of list<Json> | |
| Double of double | |
| False | |
| Integer of int64 | |
| Null | |
| Object of list<string*Json> | |
| String of string | |
| True | |
static member inline ToJson x : Json = | |
((^a or ^b) : | |
(static member ToJson : ^a * ^b -> Json) (Null, x)) | |
static member ToJson(_: Json, x: int) = Integer (int64 x) | |
static member ToJson(_: Json, x: string) = String x | |
static member inline ToJson(_: Json, x: list<_>) = | |
Array (List.map Json.ToJson x) | |
static member inline FromJson(x: Json) = | |
((^a or ^b) : (static member FromJson : ^a * ^b -> ^a) | |
(Unchecked.defaultof<_>, x)) | |
static member FromJson(_: int, x: Json) = | |
match x with | |
| Integer x -> int x | |
| _ -> invalidArg "x" "Conversion failed." | |
static member FromJson(_: string, x: Json) = | |
match x with | |
| String x -> x | |
| _ -> invalidArg "x" "Conversion failed." | |
static member inline FromJson(_: list<_>, x: Json) = | |
match x with | |
| Array xs -> [for x in xs -> Json.FromJson x] | |
| _ -> invalidArg "x" "Conversion failed." | |
type Person = | |
{ | |
age: int | |
name: string | |
} | |
static member ToJson(_: Json, x: Person) = | |
Object [ | |
"age", Integer (int64 x.age); | |
"name", String x.name | |
] | |
static member FromJson(_:Person, j: Json) = | |
match j with | |
| Object ["age", Integer age; "name", String name] -> | |
{ age = int age; name = name } | |
| _ -> | |
failwith "Conversion failed." | |
let test = | |
let p = {name="Vladimir Putin"; age=59} | |
let r : list<Person> = Json.FromJson(Json.ToJson [p; p; p]) | |
r |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See http://t0yv0.blogspot.com/2011/12/hacking-type-classes-in-f.html for context.