Skip to content

WithBodyAsJson does not return correctly formatted json when using SystemTextJsonConverter #1446

@aholeton

Description

@aholeton

Describe the bug

When using SystemTextJsonConverter as the DefaultJsonSerializer, WithBodyAsJson does not return the expected json.

In the example below there are two servers setup slightly different. The first one is using .WithBody(person, new SystemTextJsonConverter()), which works as expected and returns the following:

{
  "first_name": "John",
  "last_name": "Smith"
}

The second one sets the DefaultJsonSerializer in the setup, and then uses .WithBodyAsJson(person), which does not work as expected and returns the following:

{
  "FirstName": "John",
  "LastName": "Smith"
}

Expected behavior:

Expect both setups to return the json formatted the same way. However, the second scenario does not seem to correctly format the json. I suspect Newtonsoft is being used and not System.Text.Json.

Test to reproduce

internal class Program
{
    private static void Main(string[] args)
    {
        var person = new Person { FirstName = "John", LastName = "Smith" };

        // scenario 1
        using var wireMockServer = WireMockServer.Start("http://localhost:2312");

        // this works as expected
        wireMockServer
            .Given(Request.Create().WithPath("/scenario1").UsingPost())
            .RespondWith(Response.Create().WithBody(person, new SystemTextJsonConverter()).WithStatusCode(HttpStatusCode.OK));

        // scenario 2
        using var wireMockServer2 = WireMockServer.Start(new WireMockServerSettings { DefaultJsonSerializer = new SystemTextJsonConverter(), Port = 2313 });

        // this does not work as expected
        wireMockServer2
            .Given(Request.Create().WithPath("/scenario2").UsingPost())
            .RespondWith(Response.Create().WithBodyAsJson(person).WithStatusCode(HttpStatusCode.OK));
    }
}

public class Person
{
    [JsonPropertyName("first_name")]
    public string FirstName { get; set; }

    [JsonPropertyName("last_name")]
    public string LastName { get; set; }
}

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions