Warm tip: This article is reproduced from serverfault.com, please click

JsonDocument Parse JsonReaderException

发布于 2020-11-27 11:39:24

I thought I found a cleaner way with a smaller footprint to test a string to see if its valid JSON; however when I run a test its failing because its returns a JsonReaderException so when I tried to change the type to this, I get a protection error as it seems to be internal??

I am using System.Text.Json in my project.

How can this be changed so I can use my existing code:

    public ApplicationSettings WithTemplate(string template) {

    try {
        JsonDocument.Parse(template);
        baseTemplate = template;
    }
    catch(JsonException ex) {
        throw ex;
    }
    return this;
}

Test Code:

[Fact]
public void WithTemplate_ThrowsJsonExceptionWhenBaseTemplateIsInvalid() {
    Assert.Throws<JsonException>(() => new ApplicationSettings()
                                    .WithTemplate("345[]{}q345"));

}
Questioner
user1574598
Viewed
0
user1574598 2020-11-29 03:24:50

I found a solution that was just as compact as JsonDocument.Parse() for just checking the validity of string of json with the JsonSerializer.

string malformedJson = "345[]{}q345"

JsonSerializer.Deserialize<object>(malformedJson)

Then I was able to test against the exception JsonException and not have to worry about JsonReaderException