System.Text.Json 常规用法

安装 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
 */

文档

posted @ 2021-12-22 18:31  雨水的命运  阅读(7367)  评论(1编辑  收藏  举报