System.Text.Json 常規用法
阿新 • • 發佈:2021-12-22
安裝System.Text.Json
-
如果專案是.NET Core。需要.netcore 3.0及以上版本。
-
如果專案是.NET Standard或.NET Framework。需要安裝System.Text.JsonNuGet包。
常用using
using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Nodes;
常用方法
Utf8JsonReader - 讀操作,快速,低階
Utf8JsonWriter - 寫操作,快速,低階
JsonDocument - 基於DOM解析,快速
JsonSeriliazer - 序列化/反序列化,快速
序列化
//序列化 物件 -> JSON 字串 string json = JsonSerializer.Serialize(object); //分序列化 JSON 字串 -> 物件 var obj = JsonSerializer.Deserialize<object>(json);
特性
[JsonPropertyName("temp")] [JsonIgnore]// 不序列化這個屬性 [DisplayName("學生")] public string Student { get; set; }
全域性配置
public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddJsonOptions(options=> { // 整齊列印 options.JsonSerializerOptions.WriteIndented = true; // 忽略值為Null的屬性 options.JsonSerializerOptions.IgnoreNullValues = true; // 設定Json字串支援的編碼,預設情況下,序列化程式會轉義所有非 ASCII 字元。 即,會將它們替換為 \uxxxx,其中 xxxx 為字元的 Unicode // 程式碼。 可以通過設定Encoder來讓生成的josn字串不轉義指定的字符集而進行序列化 下面指定了基礎拉丁字母和中日韓統一表意文字的基礎Unicode 塊// (U+4E00-U+9FCC)。 基本涵蓋了除使用西裡爾字母以外所有西方國家的文字和亞洲中日韓越的文字 options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs); // 反序列化不區分大小寫 options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; // 駝峰命名 options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; // 對字典的鍵進行駝峰命名 options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase; // 序列化的時候忽略null值屬性 options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; // 忽略只讀屬性,因為只讀屬性只能序列化而不能反序列化,所以在以json為儲存資料的介質的時候,序列化只讀屬性意義不大 options.JsonSerializerOptions.IgnoreReadOnlyFields = true; // 不允許結尾有逗號的不標準json options.JsonSerializerOptions.AllowTrailingCommas = false; // 不允許有註釋的不標準json options.JsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Disallow; // 允許在反序列化的時候原本應為數字的字串(帶引號的數字)轉為數字 options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString; // 處理迴圈引用型別,比如Book類裡面有一個屬性也是Book類 options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve; }); }
解析JSON
JsonDocument和RootElement
//建立一個物件 var Object = new { code = 0, msg = "success", data = new { total = 3, details = new { codes = new string[] { "1", "2", "3" } } } }; //物件轉字串 var json = JsonSerializer.Serialize(Object); using JsonDocument jsondocument = JsonDocument.Parse(json); var rootElement = jsondocument.RootElement; var msg = rootElement.GetProperty("msg").GetString(); Console.WriteLine(msg); var array = rootElement.GetProperty("data").GetProperty("details").GetProperty("codes").EnumerateArray(); foreach (var arr in array) Console.WriteLine(arr.GetString());
輸出
success 1 2 3
JsonNode
需要net 6.0 及以上版本
//建立一個物件 var obj = new { code = 0, msg = "success", data = new { total = 3, details = new { codes = new string[] { "1", "2", "3" } } } }; var json = JsonSerializer.Serialize(obj); var jsonNode = JsonNode.Parse(json); var msg = jsonNode["msg"].ToString(); int code = jsonNode["code"].GetValue<int>(); Console.WriteLine(msg); Console.WriteLine(code); var list = jsonNode["data"]["details"]["codes"].Deserialize<string[]>(); foreach (var item in list) Console.WriteLine(item);
輸出
success 0 1 2 3TRANSLATE with x English TRANSLATE with EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back