Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace GlobalDefaultJsonSerializationoptions.Controllers;

Expand All @@ -16,6 +15,6 @@ public ActionResult CreateProduct(Product product)
[HttpPost("save")]
public ActionResult SaveProduct(Product product)
{
return Ok(JsonConvert.SerializeObject(product));
return Ok(product);
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="10.0.11" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using GlobalDefaultJsonSerializationoptions;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using GlobalDefaultJsonSerializationoptions;
using System.Text.Encodings.Web;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddControllers();

builder.Services.Configure<JsonOptions>(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.WriteIndented = false;
options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Default;
options.JsonSerializerOptions.AllowTrailingCommas = true;
options.JsonSerializerOptions.MaxDepth = 3;
options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
});
var controllers = builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.WriteIndented = false;
options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Default;
options.JsonSerializerOptions.AllowTrailingCommas = true;
options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
});

builder.Services.ConfigureHttpJsonOptions(options =>
{
Expand All @@ -30,28 +25,28 @@
options.SerializerOptions.WriteIndented = false;
options.SerializerOptions.Encoder = JavaScriptEncoder.Default;
options.SerializerOptions.AllowTrailingCommas = true;
options.SerializerOptions.MaxDepth = 3;
options.SerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
});

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
// AddNewtonsoftJson() replaces both MVC formatters, so it would take the
// System.Text.Json configuration above out of play for every controller action.
// The sample demonstrates all three approaches, so this one is registered behind
// a configuration switch: run with UseNewtonsoftJson=true to serialize controller
// responses with Json.NET instead.
if (builder.Configuration.GetValue<bool>("UseNewtonsoftJson"))
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
DateFormatString = "dd-MM-yyyy",
DefaultValueHandling = DefaultValueHandling.Ignore,
MaxDepth = 3
};
controllers.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.Formatting = Formatting.Indented;
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.DateFormatString = "dd-MM-yyyy";
options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
});
}

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();
Expand All @@ -64,3 +59,5 @@
});

app.Run();

public partial class Program;
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

Expand All @@ -10,11 +10,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.0.4" />
<PackageReference Include="MSTest.TestFramework" Version="3.0.4" />
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.11" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.9.0" />
<PackageReference Include="MSTest.TestAdapter" Version="4.3.3" />
<PackageReference Include="MSTest.TestFramework" Version="4.3.3" />
<PackageReference Include="coverlet.collector" Version="10.0.1" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System.Text;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace GlobalDefaultJsonSerializationoptionsUnitTests;

[TestClass]
public class GlobalJsonOptionsIntegrationTests
{
private const string RequestBody = """
{
"Id": 1,
"Name": null,
"Price": 0,
"Quantity": "5",
"ReleaseDate": "2024-04-14T10:49:31.813Z",
"Manufacturer": { "Name": "Apple", "Location": "California" }
}
""";

private static HttpContent JsonContent() =>
new StringContent(RequestBody, Encoding.UTF8, "application/json");

private static WebApplicationFactory<Program> CreateFactory(bool useNewtonsoftJson) =>
new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
builder.UseSetting("UseNewtonsoftJson", useNewtonsoftJson.ToString()));

private static async Task<JsonObject> PostAsync(HttpClient client, string route)
{
var response = await client.PostAsync(route, JsonContent());
var body = await response.Content.ReadAsStringAsync();

Assert.IsTrue(response.IsSuccessStatusCode, body);

return JsonNode.Parse(body)!.AsObject();
}

[TestMethod]
public async Task GivenSystemTextJsonOptions_WhenControllerActionResponds_ThenItAppliesTheConfiguredOptions()
{
using var factory = CreateFactory(useNewtonsoftJson: false);
using var client = factory.CreateClient();

var payload = await PostAsync(client, "/api/Product");

// Camel casing, nulls dropped, and a number read from a string.
CollectionAssert.AreEquivalent(
new[] { "id", "price", "quantity", "releaseDate", "manufacturer" },
payload.Select(property => property.Key).ToArray());
Assert.AreEqual(5, (int)payload["quantity"]!);
Assert.AreEqual("Apple", (string?)payload["manufacturer"]!["name"]);

// The Newtonsoft date format is not registered on this run.
Assert.AreNotEqual("14-04-2024", (string?)payload["releaseDate"]);
}

[TestMethod]
public async Task GivenNewtonsoftJsonIsRegistered_WhenControllerActionResponds_ThenJsonNetWritesTheResponse()
{
using var factory = CreateFactory(useNewtonsoftJson: true);
using var client = factory.CreateClient();

var payload = await PostAsync(client, "/api/Product/save");

// AddNewtonsoftJson() replaced the MVC formatters: Json.NET's date format
// and DefaultValueHandling.Ignore are both visible in the response.
CollectionAssert.AreEquivalent(
new[] { "id", "quantity", "releaseDate", "manufacturer" },
payload.Select(property => property.Key).ToArray());
Assert.AreEqual("14-04-2024", (string?)payload["releaseDate"]);
}

[TestMethod]
public async Task GivenNewtonsoftJsonIsRegistered_WhenMinimalApiEndpointResponds_ThenHttpJsonOptionsStillApply()
{
using var factory = CreateFactory(useNewtonsoftJson: true);
using var client = factory.CreateClient();

var payload = await PostAsync(client, "/api/Product/create");

// MVC options and Http JSON options do not cascade: the minimal API
// endpoint keeps serializing with System.Text.Json.
CollectionAssert.AreEquivalent(
new[] { "id", "price", "quantity", "releaseDate", "manufacturer" },
payload.Select(property => property.Key).ToArray());
Assert.AreNotEqual("14-04-2024", (string?)payload["releaseDate"]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using GlobalDefaultJsonSerializationoptions.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;

namespace GlobalDefaultJsonSerializationoptionsUnitTests;

Expand Down Expand Up @@ -42,8 +41,6 @@ public void GivenValidProduct_WhenSaveProductIsCalled_ThenReturnsProductWithSame
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(200, result.StatusCode);

var expectedJson = JsonConvert.SerializeObject(product);
Assert.AreEqual(expectedJson, result?.Value?.ToString());
Assert.AreEqual(product, result.Value);
}
}
Loading