Skip to content

Instantly share code, notes, and snippets.

@panesofglass
Forked from t0yv0/JsonClasses.fs
Created April 27, 2012 17:06
Show Gist options
  • Save panesofglass/2510865 to your computer and use it in GitHub Desktop.
Save panesofglass/2510865 to your computer and use it in GitHub Desktop.
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