本文主要介绍.NET Core 3.0中,使用JsonSerializer(System.Text.Json)对JSON数据进行序列化和反序列化的方法及示例代码。

1、使用的命名空间

using System.Text.Json;
using System.Text.Json.Serialization;

2、.NET对象序列化JSON字符串

将 JSON 写入字符串,请调用 JsonSerializer.Serialize 方法。 下面的示例使用具有泛型类型参数的重载:

WeatherForecast weatherForecast;
//...
string json = JsonSerializer.Serialize<WeatherForecast>(weatherForecast);

可以省略泛型类型参数并改用泛型类型推理

WeatherForecast weatherForecast;
//...
string json = JsonSerializer.Serialize(weatherForecast);

示例类型,其中包含集合和嵌套类

public class WeatherForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public IList<DateTimeOffset> DatesAvailable { get; set;}
public Dictionary<string, HighLowTemperatures> TemperatureRanges { get; set; }
public string [] SummaryWords { get; set; }
}
public class HighLowTemperatures
{
public Temperature High { get; set; }
public Temperature Low { get; set; }
}
public class Temperature
{
public int DegreesCelsius { get; set; }
}

JSON字符串

{"Date":"2019-08-01T00:00:00-07:00","TemperatureC":25,"Summary":"Hot","DatesAvailable":["2019-08-01T00:00:00-07:00","2019-08-02T00:00:00-07:00"],"TemperatureRanges":{"Cold":{"High":{"DegreesCelsius":20},"Low":{"DegreesCelsius":-10}},"Hot":{"High":{"DegreesCelsius":60},"Low":{"DegreesCelsius":20}}},"SummaryWords":["Cool","Windy","Humid"]}

序列化为UTF-8字节数据

调用 JsonSerializer.SerializeToUtf8Bytes 方法:

byte[] utf8Json = JsonSerializer.SerializeToUtf8Bytes<WeatherForecast>(weatherForecast);

序列化为 UTF-8 比使用基于字符串的方法更快5-10%。 不同之处在于,不需要将字节(如 UTF-8)转换为字符串(UTF-16)。

3、JSON字符串反序列化成.NET对象

从字符串进行反序列化,请调用 JsonSerializer.Deserialize 方法,如以下示例中所示:

string json = ... ;
var weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(json);

从UTF-8字节数据反序化

byte[] utf8Json;
//...
var readOnlySpan = new ReadOnlySpan<byte>(utf8Json);
weatherForecast = JsonSerializer.Deserialize<WeatherForecastMin>(readOnlySpan);

byte[] utf8Json;
//...
var utf8Reader = new Utf8JsonReader(utf8Json);
weatherForecast = JsonSerializer.Deserialize<WeatherForecastMin>(ref utf8Reader);

4、序列化为格式化的JSON字符串

要整齐地打印 JSON 输出,请将 JsonSerializerOptions.WriteIndented 设置为 true:

var options = new JsonSerializerOptions
{
WriteIndented = true,
};
json = JsonSerializer.Serialize(weatherForecast, options);

下面是要序列化的示例类型和 JSON 输出

class WeatherForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
}

格式化后的输出的JSON字符串

{
"Date": "2019-08-01T00:00:00-07:00",
"TemperatureC": 25,
"Summary": "Hot"
}

官方文档https://docs.microsoft.com/zh-cn/dotnet/standard/serialization/system-text-json-how-to

相关文档NET Core 3.0 JsonSerializer(System.Text.Json)自定属性名及允许注释和尾随逗号方法