C#之System.Text.Json的用法

System.Text.Json 是 C# 中的一个 JSON 序列化和反序列化库,它在 .NET Core 3.0 及更高版本中提供了内置支持。以下是 System.Text.Json 的用法详解:
JSON 序列化
JSON 序列化是将 .NET 对象转换为 JSON 字符串的过程。

using System;
using System.Text.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        var person = new Person
        {
            Name = "John",
            Age = 30
        };

        string jsonString = JsonSerializer.Serialize(person);
        Console.WriteLine(jsonString);
    }
}

上述代码中,我们定义了一个 Person 类,然后使用 JsonSerializer.Serialize 方法将 person 对象转换为 JSON 字符串。
反序列化
JSON 反序列化是将 JSON 字符串转换回 .NET 对象的过程。

using System;
using System.Text.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        string jsonString = "{\"Name\":\"John\",\"Age\":30}";

        Person person = JsonSerializer.Deserialize<Person>(jsonString);
        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
    }
}


上述代码中,我们使用 JsonSerializer.Deserialize 方法将 JSON 字符串转换为 Person 对象。
高级用法
System.Text.Json 还提供了许多高级选项,以控制序列化和反序列化过程。您可以使用 JsonSerializerOptions 来自定义行为,如命名策略、空值处理、日期时间格式化等。

var options = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = true, // 格式化输出
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
    Converters = { new MyCustomConverter() }
};

string jsonString = JsonSerializer.Serialize(person, options);

自定义转换器

public class MyCustomConverter : JsonConverter<MyType>
{
    public override MyType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        // 反序列化逻辑
    }

    public override void Write(Utf8JsonWriter writer, MyType value, JsonSerializerOptions options)
    {
        // 序列化逻辑
    }
}


然后,将自定义转换器添加到 JsonSerializerOptions 中,如前面的示例所示。

这些是 System.Text.Json 的一些基本用法和高级功能。它提供了一种轻量级且高性能的方式来处理 JSON 数据,适用于序列化和反序列化任务。在开发中,您可以根据需要使用它来与 JSON 数据进行交互。
最后需要注意的是:反序列化是case-sensitive的。
如果要设置为noncase-sensitive:

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

public class CaseInsensitivePropertyConverter<T> : JsonConverter<T>
{
    public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.StartObject)
        {
            using (JsonDocument doc = JsonDocument.ParseValue(ref reader))
            {
                var root = doc.RootElement;
                var obj = Activator.CreateInstance<T>();

                foreach (var property in root.EnumerateObject())
                {
                    var propertyName = property.Name;
                    var propertyValue = property.Value;

                    var propertyInfo = typeof(T).GetProperty(propertyName, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                    if (propertyInfo != null)
                    {
                        object value = JsonSerializer.Deserialize(propertyValue.GetRawText(), propertyInfo.PropertyType);
                        propertyInfo.SetValue(obj, value);
                    }
                }
                return obj;
            }
        }

        throw new JsonException("Expected start of an object.");
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize(writer, value, options);
    }
}

public class QRInfo
{
    public string qqrStr { get; set; }
    public decimal priwce { get; set; }
}

public class Program
{
    public static void Main()
    {
        var options = new JsonSerializerOptions();
        options.Converters.Add(new CaseInsensitivePropertyConverter<QRInfo>());

        var testStr = "{\"qqrStr\":\"gkjfdsgjffdsljgfdskljgfdklj",\"priwce\":0.01}";
        var qrInfoTest = JsonSerializer.Deserialize<QRInfo>(testStr, options);

        Console.WriteLine(qrInfoTest.qqrStr);  
        Console.WriteLine(qrInfoTest.priwce);  
    }
}




posted @ 2023-10-25 13:22  JohnYang819  阅读(1847)  评论(0编辑  收藏  举报