Skip to content

Instantly share code, notes, and snippets.

@Horusiath
Last active February 14, 2020 12:08
Show Gist options
  • Select an option

  • Save Horusiath/d3ddb341778ff599b122e5d2b95c3b9f to your computer and use it in GitHub Desktop.

Select an option

Save Horusiath/d3ddb341778ff599b122e5d2b95c3b9f to your computer and use it in GitHub Desktop.
open System
open System.Text.Json
open FsCheck.Xunit
open Newtonsoft.Json
open Swensen.Unquote
[<Property>]
let ``Parsing strings: System.Text.Json`` (i: char[]) =
let sb = System.Text.StringBuilder()
for c in i do
match c with
| '\\' -> sb.Append('\\').Append('\\') |> ignore
| '"' -> sb.Append('\\').Append('"') |> ignore
| c -> sb.Append(c) |> ignore
let expected = sb.ToString()
let actual = JsonDocument.Parse (sprintf "\"%s\"" expected)
Assertions.test <@ actual.RootElement.GetString() = (String i) @>
[<Property>]
let ``Parsing strings: Newtonsoft.Json`` (i: char[]) =
let sb = System.Text.StringBuilder()
for c in i do
match c with
| '\\' -> sb.Append('\\').Append('\\') |> ignore
| '"' -> sb.Append('\\').Append('"') |> ignore
| c -> sb.Append(c) |> ignore
let expected = sb.ToString()
let actual = JsonConvert.DeserializeObject<string> (sprintf "\"%s\"" expected)
Assertions.test <@ actual = (String i) @>
@eiriktsarpalis
Copy link

I suppose you're refering to this failure:

System.Text.Json.JsonReaderException : '0x09' is invalid within a JSON string. The string should be correctly escaped.

I think what's happening here is that Newtonsoft is more tolerant of improperly escaped json strings. Note that if I slightly change your tests to the following:

[<Property>]
let ``JsonDocument-Parse should parse Newtonsoft json strings`` (input : char[]) =
    let expected = String input
    let jsonStringLiteral = Newtonsoft.Json.JsonConvert.SerializeObject(expected)
    let actual = System.Text.Json.JsonDocument.Parse(jsonStringLiteral)
    Assert.Equal(expected, actual.RootElement.GetString())

Then it always passes without issue. I'll file an issue regardless.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment