7 people like it.

Lightweight syntax for creating JSon objects using Newtonsoft's Json.Net

There's an easy way to create JSon objects using Newtonsoft's Json.Net. The common problem with Json.Net is that there's usualy a lot of overhead when creating Json with it as there're a lot of 'new', parentheses, nested objects when we don't need them. And it becomes annoying quite fast. DU Json and toJson function allow to create Json tree and convert it to Json.Net JObject hierarchy. On the examples the usage of lightweight syntax doesn't give a lot of win but it will be more clearer when it come to more complicated objects.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
58: 
59: 
60: 
61: 
62: 
63: 
64: 
#if INTERACTIVE
#r @"Newtonsoft.Json.dll"
#endif

open Newtonsoft.Json.Linq

type Json =
    | JObj of Json seq
    | JProp of string * Json
    | JArr of Json seq
    | JVal of obj

let (!!) (o: obj) = JVal o

let rec toJson = function
    | JVal v -> new JValue(v) :> JToken
    | JProp(name, v) -> 
        match v with
        | JVal _ | JArr _ | JObj _ -> new JProperty(name, toJson v) :> JToken
        | JProp _ -> new JProperty(name, new JObject(toJson v)) :> JToken
    | JArr items -> new JArray(items |> Seq.map toJson) :> JToken
    | JObj props -> new JObject(props |> Seq.map toJson) :> JToken

// Suppose we want to create the following Json object:
// {
//     "id": 123,
//     "props": {
//         "prop": [
//             { "id": 1, v: 123 },
//             { "id": 2, v: 456 }
//         ]
//     }
// }
//
// Then the simplified lightweight Json creation will look like this:
let j =
    JObj [
        JProp("id", !! "123");
        JProp(
            "props", 
            JProp(
                "prop", 
                JArr [
                    JObj [JProp("id", !! 1); JProp("v", !! 123)];
                    JObj [JProp("id", !! 2); JProp("v", !! 456)]
                ]))
    ]

let json = toJson j

// Compare it to pure Json.Net.
let jj = 
    new JObject([
        new JProperty("id", "123");
        new JProperty(
            "props",
            new JObject(
                new JProperty(
                    "prop",
                    new JArray([
                        new JObject([new JProperty("id", 1); new JProperty("v", 123)]);
                        new JObject([new JProperty("id", 2); new JProperty("v", 456)])
                    ]))))
    ])
namespace Newtonsoft
namespace Newtonsoft.Json
namespace Newtonsoft.Json.Linq
type Json =
  | JObj of seq<Json>
  | JProp of string * Json
  | JArr of seq<Json>
  | JVal of obj

Full name: Script.Json
union case Json.JObj: seq<Json> -> Json
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
union case Json.JProp: string * Json -> Json
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
union case Json.JArr: seq<Json> -> Json
union case Json.JVal: obj -> Json
type obj = System.Object

Full name: Microsoft.FSharp.Core.obj
val o : obj
val toJson : _arg1:Json -> JToken

Full name: Script.toJson
val v : obj
Multiple items
type JValue =
  inherit JToken
  new : other:JValue -> JValue + 10 overloads
  member CompareTo : obj:JValue -> int
  member Equals : other:JValue -> bool + 1 overload
  member GetHashCode : unit -> int
  member HasValues : bool
  member ToString : unit -> string + 3 overloads
  member Type : JTokenType
  member Value : obj with get, set
  member WriteTo : writer:JsonWriter * [<ParamArray>] converters:JsonConverter[] -> unit
  static member CreateComment : value:string -> JValue
  ...

Full name: Newtonsoft.Json.Linq.JValue

--------------------
JValue(other: JValue) : unit
   (+0 other overloads)
JValue(value: int64) : unit
   (+0 other overloads)
JValue(value: uint64) : unit
   (+0 other overloads)
JValue(value: float) : unit
   (+0 other overloads)
JValue(value: System.DateTime) : unit
   (+0 other overloads)
JValue(value: bool) : unit
   (+0 other overloads)
JValue(value: string) : unit
   (+0 other overloads)
JValue(value: System.Guid) : unit
   (+0 other overloads)
JValue(value: System.Uri) : unit
   (+0 other overloads)
JValue(value: System.TimeSpan) : unit
   (+0 other overloads)
type JToken =
  member AddAfterSelf : content:obj -> unit
  member AddBeforeSelf : content:obj -> unit
  member AfterSelf : unit -> IEnumerable<JToken>
  member Ancestors : unit -> IEnumerable<JToken>
  member BeforeSelf : unit -> IEnumerable<JToken>
  member Children : unit -> JEnumerable<JToken> + 1 overload
  member CreateReader : unit -> JsonReader
  member DeepClone : unit -> JToken
  member First : JToken
  member HasValues : bool
  ...

Full name: Newtonsoft.Json.Linq.JToken
val name : string
val v : Json
Multiple items
type JProperty =
  inherit JContainer
  new : other:JProperty -> JProperty + 2 overloads
  member Name : string
  member Type : JTokenType
  member Value : JToken with get, set
  member WriteTo : writer:JsonWriter * [<ParamArray>] converters:JsonConverter[] -> unit
  static member Load : reader:JsonReader -> JProperty

Full name: Newtonsoft.Json.Linq.JProperty

--------------------
JProperty(other: JProperty) : unit
JProperty(name: string, [<System.ParamArray>] content: obj []) : unit
JProperty(name: string, content: obj) : unit
Multiple items
type JObject =
  inherit JContainer
  new : unit -> JObject + 3 overloads
  member Add : propertyName:string * value:JToken -> unit
  member GetEnumerator : unit -> IEnumerator<KeyValuePair<string, JToken>>
  member Item : obj -> JToken with get, set
  member Item : string -> JToken with get, set
  member Properties : unit -> IEnumerable<JProperty>
  member Property : name:string -> JProperty
  member PropertyValues : unit -> JEnumerable<JToken>
  member Remove : propertyName:string -> bool
  member TryGetValue : propertyName:string * value:JToken -> bool
  ...

Full name: Newtonsoft.Json.Linq.JObject

--------------------
JObject() : unit
JObject(other: JObject) : unit
JObject([<System.ParamArray>] content: obj []) : unit
JObject(content: obj) : unit
val items : seq<Json>
Multiple items
type JArray =
  inherit JContainer
  new : unit -> JArray + 3 overloads
  member Add : item:JToken -> unit
  member Clear : unit -> unit
  member Contains : item:JToken -> bool
  member IndexOf : item:JToken -> int
  member Insert : index:int * item:JToken -> unit
  member Item : obj -> JToken with get, set
  member Item : int -> JToken with get, set
  member Remove : item:JToken -> bool
  member RemoveAt : index:int -> unit
  ...

Full name: Newtonsoft.Json.Linq.JArray

--------------------
JArray() : unit
JArray(other: JArray) : unit
JArray([<System.ParamArray>] content: obj []) : unit
JArray(content: obj) : unit
module Seq

from Microsoft.FSharp.Collections
val map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map
val props : seq<Json>
val j : Json

Full name: Script.j
val json : JToken

Full name: Script.json
val jj : JObject

Full name: Script.jj
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/be
Posted:12 years ago
Author:Dmitry Lobanov
Tags: json