Created
May 16, 2019 09:16
-
-
Save MangelMaxime/4b5aa839b06633b349ad156705503f9c to your computer and use it in GitHub Desktop.
Demontraste how to store a section of a JSON without decoding/validating it
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
module Tests.Main | |
open Expecto | |
open Util.Testing | |
open Thoth.Json.Net | |
let json = | |
""" | |
{ | |
"name": "Test HTTP Scenario", | |
"baseUrl": "http://localhost:55042", | |
"requests": [ | |
{ | |
"url": "/api/ticket" | |
}, | |
{ | |
"url": "/api/ticket/", | |
"method": "POST", | |
"body": { | |
"id": "1", | |
"title": "Test ticket 1" | |
} | |
}, | |
{ | |
"url": "/api/ticket/1", | |
"method": "PUT", | |
"body": { | |
"id": "1", | |
"title": "Test ticket 1 updated" | |
} | |
}, | |
{ | |
"url": "/api/ticket/1", | |
"method": "DELETE" | |
} | |
] | |
} | |
""" | |
type Request = | |
{ Url : string | |
Method : string option | |
Body : JsonValue option } | |
static member Decoder = | |
Decode.object (fun get -> | |
{ Url = get.Required.Field "url" Decode.string | |
Method = get.Optional.Field "method" Decode.string | |
Body = get.Optional.Field "body" Decode.value } | |
) | |
type Test = | |
{ Name : string | |
BaseUrl : string | |
Requests : Request list } | |
static member Decoder = | |
Decode.object (fun get -> | |
{ Name = get.Required.Field "name" Decode.string | |
BaseUrl = get.Required.Field "baseUrl" Decode.string | |
Requests = get.Required.Field "requests" (Decode.list Request.Decoder) } | |
) | |
let printRequest (request : Request) = | |
printfn "----- PRINT REQUEST -----" | |
printfn "" | |
printfn "" | |
printfn "Url: %s" request.Url | |
match request.Method with | |
| Some method -> | |
printfn "Method: %s" method | |
| None -> | |
printfn "No method provided" | |
match request.Body with | |
| Some body -> | |
printfn "Body: %s" (body.ToString()) | |
| None -> | |
printfn "No body provided" | |
[<EntryPoint>] | |
let main args = | |
// testList "All" [ Tests.Decoders.tests | |
// Tests.Encoders.tests | |
// ] | |
// |> runTestsWithArgs defaultConfig args | |
let test = Decode.unsafeFromString Test.Decoder json | |
test.Requests | |
|> List.iter printRequest | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here the goal is to decode the provided
json
. The tricky point is we don't know what type isbody
.In order to still keep
body
reference/value, we are going to store directly theJsonValue
provided by Newtonsoft. Like that we can later retrieve the content ofbody
by doingbody.ToString()
for example.Running the above code returns: