.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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章