.NET Core 3.0中的Json API : System.Text.Json

.NET Core 3.0 中的Json API : System.Text.Json

System.Text.Json 命名空间提供高性能、低分配以及符合标准的功能来处理 JavaScript 对象表示法 (JSON),其中包括将对象序列化为 JSON 文本以及将 JSON 文本反序列化为对象(内置 UTF-8 支持)。 它还提供类型以用于读取和写入编码为 UTF-8 的 JSON 文本,以及用于创建内存中文档对象模型 (DOM) 以在数据的结构化视图中随机访问 JSON 元素。引用自:System.Text.Json 命名空间

基本的序列化和反序列化

public static string Serialize()
{
    var rng = new Random();
    WeatherForecast weatherForecast = new WeatherForecast
    {
        Location = "Hangzhou",
        Temperature = rng.Next(-10, 45),
        Date = DateTimeOffset.UtcNow,
    };
    return JsonSerializer.Serialize(weatherForecast);
}

public static string GetSummary()
{
    var json = "{\"Location\":\"Hangzhou\",\"Temperature\":4,\"Date\":\"2019-11-19T11:55:46.0310797+00:00\"}";
    var weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(json);
    return $"{weatherForecast.Location} {weatherForecast.Date.ToLocalTime().ToString("yyyy年MM月dd日")}的温度是{weatherForecast.Temperature} ℃";
}
class WeatherForecast
{
    public string Location { get; set; }
    public int Temperature { get; set; }
    public DateTimeOffset Date { get; set; }
}

参考

Try the new System.Text.Json APIs

发布了110 篇原创文章 · 获赞 36 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/zhaobw831/article/details/103148817