安裝 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; }
配置
局部配置
var options = new JsonSerializerOptions
{
WriteIndented = true,
Converters =
{
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
}
};
string jsonString = JsonSerializer.Serialize(weatherForecast, options);
全局配置
API返回結果配置
services.AddControllers()
.AddJsonOptions(options =>
{
// 整齊打印
options.JsonSerializerOptions.WriteIndented = true;
// 關閉轉義,默認情況下,序列化程序會轉義所有非 ASCII 字符。 即,會將中文替換為 \uxxxx,其中 xxxx 為字符的 Unicode 代碼。
options.JsonSerializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
// 反序列化不區分大小寫
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;
// 處理循環引用類型
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
//類型轉換
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
});
常規用法
字段全部小寫
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = LowerCaseNamingPolicy.Instance
};
string jsonString = JsonSerializer.Serialize(obj, options);
public class LowerCaseNamingPolicy : JsonNamingPolicy
{
public static LowerCaseNamingPolicy Instance { get; } = new LowerCaseNamingPolicy();
public override string ConvertName(string name) => name.ToLower();
}
蛇形命名法
public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();
public override string ConvertName(string name)
{
return string.Concat(name.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();
}
}
時間類型格式化
添加DateTimeConverter
public class SystemTextJsonConvert
{
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
public class DateTimeNullableConverter : JsonConverter<DateTime?>
{
public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return string.IsNullOrEmpty(reader.GetString()) ? default(DateTime?) : DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
{
writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
}
在字段中添加配置
[JsonConverter(typeof(DateTimeConverter))]
在JsonSerializerOptions
添加配置
JsonSerializerOptions options = new JsonSerializerOptions()
{
Converters = { new DateTimeConverter() }
};
var json = JsonSerializer.Serialize(obj, options);
枚舉返回字符串
添加特性
public class TestEnmu
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public NotifyType Type { get; set; }
}
public enum NotifyType
{
Mail = 0,
SMS = 1
}
或者添加轉換配置
//獲取枚舉字符串並使用駝峰命名法
var options = new JsonSerializerOptions
{
Converters =
{
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
}
};
解析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>();
string two = jsonNode["data"]["details"]["codes"][1].ToString();
Console.WriteLine(msg);
Console.WriteLine(code);
Console.WriteLine(two);
Console.WriteLine("---------------------------------------------------------");
var list = jsonNode["data"]["details"]["codes"].Deserialize<string[]>();
foreach (var item in list)
Console.WriteLine(item);
輸出
/*
success
0
2
---------------------------------------------------------
1
2
3
*/