TOC
Summary
What is System.Text.Json.JsonSerializer
class?
I’ve been using JSON.NET by Newtonsoft in .NET Framework v4, but I’m not familiar with the above class.
So, I try to use System.Text.Json.JsonSerializer class.
Prerequisites
- Azure Functions v3
- Microsoft.NET.Sdk.Functions v3.0.13
- netcoreapp3.1
- C# 8
- .NET Core v3.1
- Visual Studio 2019
- Windows 10 v21H1
Steps
A simply usage of System.Text.Json
is as follows:
- Define a class as entity.
- If you want to control property name of JSON, adding
JsonPropertyName
attribute. It will need to useSystem.Text.Json.Serialization
namespace.
- If you want to control property name of JSON, adding
- Serialize a defined entity class with
System.Text.Json.JsonSerializer.Serialize
.
Entity sample
Example is here:
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Sample
{
public enum ProductType
{
Book,
Album,
Cinema
}
public class Product
{
[JsonPropertyName("id")]
public Guid Id { get; set; }
[JsonPropertyName("type")]
public ProductType Type { get; set; }
[JsonPropertyName("is_ready")]
public bool IsReady { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("revision")]
public int Revision { get; set; }
[JsonPropertyName("authors")]
public IList<string> Authors { get; set; }
[JsonPropertyName("registed_at")]
public DateTime RegistedAt { get; set; }
[JsonPropertyName("updated_at")]
public DateTime UpdatedAt { get; set; }
}
}
API (Function class)
The following sample api has convert the Product class to json text with JsonSerializer.Serialize
. When you access this api by your web browser, you will see the JSON as text.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace Sample
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var product = new Product
{
Id = Guid.NewGuid(),
Type = ProductType.Cinema,
IsReady = false,
Name = "羅生門",
Revision = 1,
Authors = new List<string> { "黒澤 明", "橋本 忍" },
RegistedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};
var json = JsonSerializer.Serialize(product);
string responseMessage = json;
return new OkObjectResult(responseMessage);
}
}
}
Result
{"id":"943fd8e5-86a2-4211-8891-e54be8fba0ef","type":2,"is_ready":false,"name":"\u7F85\u751F\u9580","revision":1,"authors":["\u9ED2\u6FA4 \u660E","\u6A4B\u672C \u5FCD"],"registed_at":"2021-10-12T13:29:59.1298115Z","updated_at":"2021-10-12T13:29:59.1298456Z"}
Next, I’ll try to use theJsonSerializerOptions
class. It may have useful features.