From 77ee80e078c49a3b2e924d0700c799b024353362 Mon Sep 17 00:00:00 2001 From: Vladimir Pecanac Date: Sun, 29 Nov 2026 20:24:56 +0100 Subject: [PATCH] Add IntroductionToSystemTextJson sample (migrated, net11.0, tests) Migrates the System.Text.Json introduction sample from its standalone repository into json-csharp. Console project on top-level statements, Web API on minimal hosting with Microsoft.AspNetCore.OpenApi instead of Swashbuckle, a named HttpClient on localhost:5000, POST examples for PostAsJsonAsync, and a new xUnit test project (ten tests, WebApplicationFactory in process). --- .../IntroductionToSystemTextJson.sln | 67 ++++++++ .../JsonExampleProject1.csproj | 10 ++ .../JsonExampleProject1/Person.cs | 12 ++ .../JsonExampleProject1/Pet.cs | 10 ++ .../JsonExampleProject1/Program.cs | 146 ++++++++++++++++++ .../Controllers/TestClientController.cs | 26 ++++ .../Controllers/TestController.cs | 37 +++++ .../JsonExampleProject2.csproj | 13 ++ .../JsonExampleProject2.http | 18 +++ .../JsonExampleProject2/Person.cs | 18 +++ .../JsonExampleProject2/Pet.cs | 13 ++ .../JsonExampleProject2/Program.cs | 22 +++ .../Properties/launchSettings.json | 23 +++ .../appsettings.Development.json | 8 + .../JsonExampleProject2/appsettings.json | 9 ++ .../ConsoleExampleTests.cs | 105 +++++++++++++ .../IntroductionToSystemTextJson.Tests.csproj | 27 ++++ .../WebApiExampleTests.cs | 53 +++++++ 18 files changed, 617 insertions(+) create mode 100644 json-csharp/IntroductionToSystemTextJson/IntroductionToSystemTextJson.sln create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/JsonExampleProject1.csproj create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Person.cs create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Pet.cs create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Program.cs create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Controllers/TestClientController.cs create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Controllers/TestController.cs create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/JsonExampleProject2.csproj create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/JsonExampleProject2.http create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Person.cs create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Pet.cs create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Program.cs create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Properties/launchSettings.json create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/appsettings.Development.json create mode 100644 json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/appsettings.json create mode 100644 json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/ConsoleExampleTests.cs create mode 100644 json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/IntroductionToSystemTextJson.Tests.csproj create mode 100644 json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/WebApiExampleTests.cs diff --git a/json-csharp/IntroductionToSystemTextJson/IntroductionToSystemTextJson.sln b/json-csharp/IntroductionToSystemTextJson/IntroductionToSystemTextJson.sln new file mode 100644 index 0000000000..0fac000acf --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/IntroductionToSystemTextJson.sln @@ -0,0 +1,67 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JsonExampleProject1", "JsonExampleProject1\JsonExampleProject1.csproj", "{47CD3FE6-46A4-4266-97BF-A902CC557B43}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JsonExampleProject2", "JsonExampleProject2\JsonExampleProject2.csproj", "{70170150-85F4-46AB-BE88-AF246CD1D393}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IntroductionToSystemTextJson.Tests", "Tests\IntroductionToSystemTextJson.Tests\IntroductionToSystemTextJson.Tests.csproj", "{5CEA4121-3B47-4B52-BA36-D6CC9F549459}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Debug|Any CPU.Build.0 = Debug|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Debug|x64.ActiveCfg = Debug|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Debug|x64.Build.0 = Debug|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Debug|x86.ActiveCfg = Debug|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Debug|x86.Build.0 = Debug|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Release|Any CPU.ActiveCfg = Release|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Release|Any CPU.Build.0 = Release|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Release|x64.ActiveCfg = Release|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Release|x64.Build.0 = Release|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Release|x86.ActiveCfg = Release|Any CPU + {47CD3FE6-46A4-4266-97BF-A902CC557B43}.Release|x86.Build.0 = Release|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Debug|Any CPU.Build.0 = Debug|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Debug|x64.ActiveCfg = Debug|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Debug|x64.Build.0 = Debug|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Debug|x86.ActiveCfg = Debug|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Debug|x86.Build.0 = Debug|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Release|Any CPU.ActiveCfg = Release|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Release|Any CPU.Build.0 = Release|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Release|x64.ActiveCfg = Release|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Release|x64.Build.0 = Release|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Release|x86.ActiveCfg = Release|Any CPU + {70170150-85F4-46AB-BE88-AF246CD1D393}.Release|x86.Build.0 = Release|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Debug|x64.ActiveCfg = Debug|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Debug|x64.Build.0 = Debug|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Debug|x86.ActiveCfg = Debug|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Debug|x86.Build.0 = Debug|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Release|Any CPU.Build.0 = Release|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Release|x64.ActiveCfg = Release|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Release|x64.Build.0 = Release|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Release|x86.ActiveCfg = Release|Any CPU + {5CEA4121-3B47-4B52-BA36-D6CC9F549459}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {5CEA4121-3B47-4B52-BA36-D6CC9F549459} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + EndGlobalSection +EndGlobal diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/JsonExampleProject1.csproj b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/JsonExampleProject1.csproj new file mode 100644 index 0000000000..5bf6c9b8cf --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/JsonExampleProject1.csproj @@ -0,0 +1,10 @@ + + + + Exe + net11.0 + enable + enable + + + diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Person.cs b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Person.cs new file mode 100644 index 0000000000..da5454c609 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Person.cs @@ -0,0 +1,12 @@ +namespace JsonExampleProject1; + +public class Person +{ + public string Name { get; set; } = string.Empty; + + public int? Age { get; set; } + + public string StateOfOrigin { get; set; } = string.Empty; + + public List Pets { get; set; } = []; +} diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Pet.cs b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Pet.cs new file mode 100644 index 0000000000..f8d81c6f04 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Pet.cs @@ -0,0 +1,10 @@ +namespace JsonExampleProject1; + +public class Pet +{ + public string Type { get; set; } = string.Empty; + + public string Name { get; set; } = string.Empty; + + public double Age { get; set; } +} diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Program.cs b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Program.cs new file mode 100644 index 0000000000..afb525ca86 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject1/Program.cs @@ -0,0 +1,146 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using JsonExampleProject1; + +SerializeExample(); +await SerializeToFile(); +DeserializeExample(); +DeserializeWithJsonDocument(); +SerializeWithOptions(); +DeserializeWithOptions(); + +static void SerializeExample() +{ + var pets = new List + { + new Pet { Type = "Cat", Name = "MooMoo", Age = 3.4 }, + new Pet { Type = "Squirrel", Name = "Sandy", Age = 7 } + }; + + var person = new Person + { + Name = "John", + Age = 34, + StateOfOrigin = "England", + Pets = pets + }; + + Console.WriteLine(JsonSerializer.Serialize(person)); + Console.WriteLine(JsonSerializer.Serialize(person)); +} + +static async Task SerializeToFile() +{ + var pets = new List + { + new Pet { Type = "Cat", Name = "MooMoo", Age = 3.4 }, + new Pet { Type = "Squirrel", Name = "Sandy", Age = 7 } + }; + + var person = new Person + { + Name = "John", + Age = 34, + StateOfOrigin = "England", + Pets = pets + }; + + var fileName = "Person.json"; + + await using (var stream = File.Create(fileName)) + { + await JsonSerializer.SerializeAsync(stream, person); + } + + Console.WriteLine(File.ReadAllText(fileName)); +} + +static void DeserializeExample() +{ + var jsonPerson = """ + {"Name":"John", + "Age":34, + "StateOfOrigin":"England", + "Pets": + [{"Type":"Cat","Name":"MooMoo","Age":3.4}, + {"Type":"Squirrel","Name":"Sandy","Age":7}]} + """; + + var personObject = JsonSerializer.Deserialize(jsonPerson)!; + + Console.WriteLine($"Person's name: {personObject.Name}"); + Console.WriteLine($"Person's age: {personObject.Age}"); + Console.WriteLine($"Person's first pet's name: {personObject.Pets.First().Name}"); +} + +static void DeserializeWithJsonDocument() +{ + var unknownJsonStructure = """ + {"Product name":"Fork", + "Price": "300$", + "Categories": + [{"Area":"Kitchen","Description":"Cooking Utensil"}, + {"Area":"Dining room","Description":"Dining Utensil"}]} + """; + + using var unknownObject = JsonDocument.Parse(unknownJsonStructure); + var productName = unknownObject.RootElement.GetProperty("Product name"); + + Console.WriteLine($"Product name: {productName}"); + + var categories = unknownObject.RootElement.GetProperty("Categories"); + + Console.WriteLine("Categories: "); + + foreach (var category in categories.EnumerateArray()) + { + Console.WriteLine(category.GetProperty("Area")); + } +} + +static void SerializeWithOptions() +{ + var pets = new List + { + new Pet { Type = "Cat", Name = "MooMoo", Age = 3.4 }, + new Pet { Type = "Squirrel", Name = "Sandy", Age = 7 } + }; + + var person2 = new Person + { + Name = "John", + Age = null, + StateOfOrigin = "England", + Pets = pets + }; + + var options = new JsonSerializerOptions + { + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + + Console.WriteLine(JsonSerializer.Serialize(person2, options)); +} + +static void DeserializeWithOptions() +{ + var jsonPerson = """ + {"Name":"John", + "Age":"34", + "StateOfOrigin":"England", + "Pets": + [{"Type":"Cat","Name":"MooMoo","Age":"3.4"}, + {"Type":"Squirrel","Name":"Sandy","Age":7}]} + """; + + var options = new JsonSerializerOptions + { + NumberHandling = JsonNumberHandling.AllowReadingFromString + }; + + var personObject = JsonSerializer.Deserialize(jsonPerson, options)!; + + Console.WriteLine($"Person's age: {personObject.Age}"); + Console.WriteLine($"Person's first pet's age: {personObject.Pets.First().Age}"); +} diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Controllers/TestClientController.cs b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Controllers/TestClientController.cs new file mode 100644 index 0000000000..7ed03e874a --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Controllers/TestClientController.cs @@ -0,0 +1,26 @@ +using Microsoft.AspNetCore.Mvc; + +namespace JsonExampleProject2.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class TestClientController(IHttpClientFactory httpClientFactory) : ControllerBase +{ + [HttpGet] + public async Task GetJson() + { + var client = httpClientFactory.CreateClient("TestClientController"); + var person = await client.GetFromJsonAsync("Test"); + + return Ok(person); + } + + [HttpPost] + public async Task CreatePerson(Person person) + { + var client = httpClientFactory.CreateClient("TestClientController"); + var response = await client.PostAsJsonAsync("Test", person); + + return StatusCode((int)response.StatusCode); + } +} diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Controllers/TestController.cs b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Controllers/TestController.cs new file mode 100644 index 0000000000..fbbd5a0735 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Controllers/TestController.cs @@ -0,0 +1,37 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Mvc; + +namespace JsonExampleProject2.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class TestController : ControllerBase +{ + [HttpGet] + public string Get() + { + var pets = new List + { + new Pet { Type = "Cat", Name = "MooMoo", Age = 3.4 }, + new Pet { Type = "Squirrel", Name = "Sandy", Age = 7 } + }; + + var person = new Person + { + Name = "John", + Age = 34, + StateOfOrigin = "England", + Pets = pets + }; + + var options = new JsonSerializerOptions + { + WriteIndented = true + }; + + return JsonSerializer.Serialize(person, options); + } + + [HttpPost] + public IActionResult Post(Person person) => Ok(person); +} diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/JsonExampleProject2.csproj b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/JsonExampleProject2.csproj new file mode 100644 index 0000000000..424b588a67 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/JsonExampleProject2.csproj @@ -0,0 +1,13 @@ + + + + net11.0 + enable + enable + + + + + + + diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/JsonExampleProject2.http b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/JsonExampleProject2.http new file mode 100644 index 0000000000..2e95e6e5e6 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/JsonExampleProject2.http @@ -0,0 +1,18 @@ +@JsonExampleProject2_HostAddress = http://localhost:5000 + +GET {{JsonExampleProject2_HostAddress}}/api/Test +Accept: application/json + +### + +GET {{JsonExampleProject2_HostAddress}}/api/TestClient +Accept: application/json + +### + +POST {{JsonExampleProject2_HostAddress}}/api/TestClient +Content-Type: application/json + +{"name":"Jane","age":29,"state of origin":"Wales","pets":[{"Type":"Dog","Name":"Rex"}]} + +### diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Person.cs b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Person.cs new file mode 100644 index 0000000000..70a65a6ef0 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Person.cs @@ -0,0 +1,18 @@ +using System.Text.Json.Serialization; + +namespace JsonExampleProject2; + +public class Person +{ + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + [JsonPropertyName("age")] + public int? Age { get; set; } + + [JsonPropertyName("state of origin")] + public string StateOfOrigin { get; set; } = string.Empty; + + [JsonPropertyName("pets")] + public List Pets { get; set; } = []; +} diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Pet.cs b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Pet.cs new file mode 100644 index 0000000000..fbcec8a882 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Pet.cs @@ -0,0 +1,13 @@ +using System.Text.Json.Serialization; + +namespace JsonExampleProject2; + +public class Pet +{ + public string Type { get; set; } = string.Empty; + + public string Name { get; set; } = string.Empty; + + [JsonIgnore] + public double Age { get; set; } +} diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Program.cs b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Program.cs new file mode 100644 index 0000000000..c70673626d --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Program.cs @@ -0,0 +1,22 @@ +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddControllers(); +builder.Services.AddOpenApi(); + +builder.Services.AddHttpClient("TestClientController", + c => c.BaseAddress = new Uri("http://localhost:5000/api/")); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.MapOpenApi(); +} + +app.UseHttpsRedirection(); + +app.UseAuthorization(); + +app.MapControllers(); + +app.Run(); diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Properties/launchSettings.json b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Properties/launchSettings.json new file mode 100644 index 0000000000..c2d94ddfd1 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/appsettings.Development.json b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/appsettings.Development.json new file mode 100644 index 0000000000..0c208ae918 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/appsettings.json b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/appsettings.json new file mode 100644 index 0000000000..10f68b8c8b --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/JsonExampleProject2/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/ConsoleExampleTests.cs b/json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/ConsoleExampleTests.cs new file mode 100644 index 0000000000..1b4d8b7cca --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/ConsoleExampleTests.cs @@ -0,0 +1,105 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using JsonExampleProject1; + +namespace IntroductionToSystemTextJson.Tests; + +public class ConsoleExampleTests +{ + private static Person CreatePerson(int? age) => new() + { + Name = "John", + Age = age, + StateOfOrigin = "England", + Pets = + [ + new Pet { Type = "Cat", Name = "MooMoo", Age = 3.4 }, + new Pet { Type = "Squirrel", Name = "Sandy", Age = 7 } + ] + }; + + [Fact] + public void WhenSerializingWithDefaults_ThenOutputIsCompactAndKeepsPropertyNames() + { + var json = JsonSerializer.Serialize(CreatePerson(34)); + + Assert.Equal( + """{"Name":"John","Age":34,"StateOfOrigin":"England","Pets":[{"Type":"Cat","Name":"MooMoo","Age":3.4},{"Type":"Squirrel","Name":"Sandy","Age":7}]}""", + json); + } + + [Fact] + public void WhenWritingNullIsSet_ThenNullAgeIsLeftOut() + { + var options = new JsonSerializerOptions + { + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + + var json = JsonSerializer.Serialize(CreatePerson(null), options); + + Assert.DoesNotContain("\"Age\": null", json); + Assert.Contains("\"Age\": 3.4", json); + Assert.Contains(Environment.NewLine + " \"Name\": \"John\"", json); + } + + [Fact] + public void WhenNumbersAreQuoted_ThenAllowReadingFromStringReadsThem() + { + var json = """{"Name":"John","Age":"34","Pets":[{"Age":"3.4"}]}"""; + var options = new JsonSerializerOptions + { + NumberHandling = JsonNumberHandling.AllowReadingFromString + }; + + var person = JsonSerializer.Deserialize(json, options)!; + + Assert.Equal(34, person.Age); + Assert.Equal(3.4, person.Pets[0].Age); + } + + [Fact] + public void WhenNumbersAreQuotedAndOptionsAreDefault_ThenDeserializeThrows() + { + var json = """{"Name":"John","Age":"34"}"""; + + Assert.Throws(() => JsonSerializer.Deserialize(json)); + } + + [Fact] + public void WhenUsingWebDefaults_ThenQuotedNumbersAndCamelCaseNamesAreRead() + { + var json = """{"name":"John","age":"34"}"""; + + var person = JsonSerializer.Deserialize(json, new JsonSerializerOptions(JsonSerializerDefaults.Web))!; + + Assert.Equal("John", person.Name); + Assert.Equal(34, person.Age); + } + + [Fact] + public void WhenParsingWithJsonDocument_ThenPropertiesAreReadWithoutAClass() + { + using var document = JsonDocument.Parse( + """{"Product name":"Fork","Categories":[{"Area":"Kitchen"},{"Area":"Dining room"}]}"""); + + var areas = document.RootElement.GetProperty("Categories") + .EnumerateArray() + .Select(c => c.GetProperty("Area").GetString()) + .ToList(); + + Assert.Equal("Fork", document.RootElement.GetProperty("Product name").GetString()); + Assert.Equal(["Kitchen", "Dining room"], areas); + } + + [Fact] + public async Task WhenSerializingToAStream_ThenStreamHoldsTheSameJson() + { + using var stream = new MemoryStream(); + + await JsonSerializer.SerializeAsync(stream, CreatePerson(34)); + + Assert.Equal(JsonSerializer.Serialize(CreatePerson(34)), System.Text.Encoding.UTF8.GetString(stream.ToArray())); + } +} diff --git a/json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/IntroductionToSystemTextJson.Tests.csproj b/json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/IntroductionToSystemTextJson.Tests.csproj new file mode 100644 index 0000000000..ad6abfbad2 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/IntroductionToSystemTextJson.Tests.csproj @@ -0,0 +1,27 @@ + + + + net11.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + diff --git a/json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/WebApiExampleTests.cs b/json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/WebApiExampleTests.cs new file mode 100644 index 0000000000..ab29ccf448 --- /dev/null +++ b/json-csharp/IntroductionToSystemTextJson/Tests/IntroductionToSystemTextJson.Tests/WebApiExampleTests.cs @@ -0,0 +1,53 @@ +using System.Net; +using System.Net.Http.Json; +using JsonExampleProject2; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; + +namespace IntroductionToSystemTextJson.Tests; + +public class WebApiExampleTests(WebApplicationFactory factory) + : IClassFixture> +{ + private WebApplicationFactory FactoryWithClientOnTestServer() => + factory.WithWebHostBuilder(builder => builder.ConfigureServices(services => + services.AddHttpClient("TestClientController") + .ConfigurePrimaryHttpMessageHandler(() => factory.Server.CreateHandler()))); + + [Fact] + public async Task WhenGettingTest_ThenAttributesRenameAndIgnoreProperties() + { + var client = factory.CreateClient(); + + var body = await client.GetStringAsync("/api/Test"); + + Assert.Contains("\"state of origin\": \"England\"", body); + Assert.Contains("\"name\": \"John\"", body); + Assert.DoesNotContain("3.4", body); + } + + [Fact] + public async Task WhenGettingTestClient_ThenGetFromJsonAsyncReadsThePerson() + { + var client = FactoryWithClientOnTestServer().CreateClient(); + + var person = await client.GetFromJsonAsync("/api/TestClient"); + + Assert.NotNull(person); + Assert.Equal("John", person.Name); + Assert.Equal(34, person.Age); + Assert.Equal("England", person.StateOfOrigin); + Assert.Equal(2, person.Pets.Count); + } + + [Fact] + public async Task WhenPostingToTestClient_ThenPostAsJsonAsyncSendsThePerson() + { + var client = FactoryWithClientOnTestServer().CreateClient(); + var person = new Person { Name = "Jane", Age = 29, StateOfOrigin = "Wales" }; + + var response = await client.PostAsJsonAsync("/api/TestClient", person); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +}