如何使用 System.Text.Json 允許某種無效的 JSON
在本文中,您會了解如何在 JSON 中允許註解、後置逗號和引號數字,以及如何將數字寫入為字串。
允許註解和後置逗號
JSON 中預設不允許註解和後置逗號。 若要在 JSON 中允許註解,請將 JsonSerializerOptions.ReadCommentHandling 屬性設定為 JsonCommentHandling.Skip
。
若要允許後置逗號,請將 JsonSerializerOptions.AllowTrailingCommas 屬性設定為 true
。 下列範例示範如何允許這兩者:
var options = new JsonSerializerOptions
{
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
WeatherForecast weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(
jsonString,
options
)!;
Dim options As JsonSerializerOptions = New JsonSerializerOptions With {
.ReadCommentHandling = JsonCommentHandling.Skip,
.AllowTrailingCommas = True
}
Dim weatherForecast1 = JsonSerializer.Deserialize(Of WeatherForecast)(jsonString, options)
下列是具有註解和後置逗號的範例 JSON:
{
"Date": "2019-08-01T00:00:00-07:00",
"TemperatureCelsius": 25, // Fahrenheit 77
"Summary": "Hot", /* Zharko */
// Comments on
/* separate lines */
}
允許或寫入引號中的數字
部分序列化程式會將數字編碼為 JSON 字串 (以引號括住)。
例如:
{
"DegreesCelsius": "23"
}
而非:
{
"DegreesCelsius": 23
}
若要將引號中的數字序列化,或接受整個輸入物件圖的引號中數字,請設定 JsonSerializerOptions.NumberHandling,如下列範例所示:
using System.Text.Json;
using System.Text.Json.Serialization;
namespace QuotedNumbers
{
public class Forecast
{
public DateTime Date { get; init; }
public int TemperatureC { get; set; }
public string? Summary { get; set; }
};
public class Program
{
public static void Main()
{
Forecast forecast = new()
{
Date = DateTime.Now,
TemperatureC = 40,
Summary = "Hot"
};
JsonSerializerOptions options = new()
{
NumberHandling =
JsonNumberHandling.AllowReadingFromString |
JsonNumberHandling.WriteAsString,
WriteIndented = true
};
string forecastJson =
JsonSerializer.Serialize<Forecast>(forecast, options);
Console.WriteLine($"Output JSON:\n{forecastJson}");
Forecast forecastDeserialized =
JsonSerializer.Deserialize<Forecast>(forecastJson, options)!;
Console.WriteLine($"Date: {forecastDeserialized.Date}");
Console.WriteLine($"TemperatureC: {forecastDeserialized.TemperatureC}");
Console.WriteLine($"Summary: {forecastDeserialized.Summary}");
}
}
}
// Produces output like the following example:
//
//Output JSON:
//{
// "Date": "2020-10-23T12:27:06.4017385-07:00",
// "TemperatureC": "40",
// "Summary": "Hot"
//}
//Date: 10/23/2020 12:27:06 PM
//TemperatureC: 40
//Summary: Hot
Imports System.Text.Json
Imports System.Text.Json.Serialization
Namespace QuotedNumbers
Public Class Forecast
Public Property [Date] As Date
Public Property TemperatureC As Integer
Public Property Summary As String
End Class
Public NotInheritable Class Program
Public Shared Sub Main()
Dim forecast1 As New Forecast() With {
.[Date] = Date.Now,
.TemperatureC = 40,
.Summary = "Hot"
}
Dim options As New JsonSerializerOptions() With {
.NumberHandling = JsonNumberHandling.AllowReadingFromString Or
JsonNumberHandling.WriteAsString,
.WriteIndented = True
}
Dim forecastJson As String = JsonSerializer.Serialize(forecast1, options)
Console.WriteLine($"Output JSON:{forecastJson}")
Dim forecastDeserialized As Forecast = JsonSerializer.Deserialize(Of Forecast)(forecastJson, options)
Console.WriteLine($"Date: {forecastDeserialized.[Date]}")
Console.WriteLine($"TemperatureC: {forecastDeserialized.TemperatureC}")
Console.WriteLine($"Summary: {forecastDeserialized.Summary}")
End Sub
End Class
End Namespace
' Produces output like the following example:
'
'Output JSON:
'{
' "Date": "2020-10-23T12:27:06.4017385-07:00",
' "TemperatureC": "40",
' "Summary": "Hot"
'}
'Date: 10/23/2020 12:27:06 PM
'TemperatureC: 40
'Summary: Hot
因為 ASP.NET Core 會指定 Web 預設選項,所以在透過 ASP.NET Core 間接使用 System.Text.Json
時,會在還原序列化時允許引號數字。
若要允許或寫入特定屬性、欄位或型別的引號數字,請使用 [JsonNumberHandling] 屬性。