Skip to content
Merged
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
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -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<Pet> Pets { get; set; } = [];
}
Original file line number Diff line number Diff line change
@@ -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; }
}
Original file line number Diff line number Diff line change
@@ -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<Pet>
{
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>(person));
}

static async Task SerializeToFile()
{
var pets = new List<Pet>
{
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<Person>(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<Pet>
{
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<Person>(jsonPerson, options)!;

Console.WriteLine($"Person's age: {personObject.Age}");
Console.WriteLine($"Person's first pet's age: {personObject.Pets.First().Age}");
}
Original file line number Diff line number Diff line change
@@ -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<IActionResult> GetJson()
{
var client = httpClientFactory.CreateClient("TestClientController");
var person = await client.GetFromJsonAsync<Person>("Test");

return Ok(person);
}

[HttpPost]
public async Task<IActionResult> CreatePerson(Person person)
{
var client = httpClientFactory.CreateClient("TestClientController");
var response = await client.PostAsJsonAsync("Test", person);

return StatusCode((int)response.StatusCode);
}
}
Original file line number Diff line number Diff line change
@@ -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<Pet>
{
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);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="11.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -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"}]}

###
Original file line number Diff line number Diff line change
@@ -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<Pet> Pets { get; set; } = [];
}
Original file line number Diff line number Diff line change
@@ -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; }
}
Loading
Loading