c#:System.Text.Json 的使用四(如何忽略[JsonPropertyName])

环境:

  • .net 6.0
  • vs2022

系列篇:
《c#:System.Text.Json 的使用一》
《c#:System.Text.Json 的使用二》
《c#:System.Text.Json 的使用三(从Newtonsoft迁移)》
《c#:System.Text.Json 的使用四(如何忽略[JsonPropertyName])》
参考:
《C# 序列化Json时如何忽略JsonProperty(PropertyName =" someName")》
《自定义 JSON 协定》

1. System.Text.Json

csharp 复制代码
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Reflection;


//默认输出: {"kname":"jack"}
//var jsonDefault = JsonSerializer.Serialize(new Person { Name = "jack" });

//使用 Modifiers 达到期望, 输出: {"Name":"jack"}
var json = JsonSerializer.Serialize(new Person { Name = "jack" }, new JsonSerializerOptions
{
    TypeInfoResolver = new DefaultJsonTypeInfoResolver
    {
        Modifiers = { (typeInfo) =>
                {
                    for (int i = 0; i < typeInfo.Properties.Count; i++)
                    {
                        var property = typeInfo.Properties[i];
                        var prop = property.AttributeProvider as PropertyInfo;
                        if (prop != null) property.Name = prop.Name;
                    }
                }
        }
    }
});

public class Person
{
    [JsonPropertyName("kname")]
    public string Name { get; set; }
}

2. NewtonSoft

csharp 复制代码
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

//默认输出: {"kname":"jack"}
//var jsonDefault = JsonConvert.SerializeObject(new Person { Name = "jack" });

//使用 ContractResolver 达到期望, 输出: {"Name":"jack"}
var settings = new JsonSerializerSettings();
settings.ContractResolver = new LongNameContractResolver();
var json = JsonConvert.SerializeObject(new Person { Name = "jack" }, settings);

public class Person
{
    [JsonProperty("kname")]
    public string Name { get; set; }
}

public class LongNameContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);
        foreach (JsonProperty prop in list)
        {
            prop.PropertyName = prop.UnderlyingName;
        }
        return list;
    }
}
相关推荐
懒人咖5 小时前
缺料分析时携带用料清单的二开字段
c#·金蝶云星空
小韩学长yyds6 小时前
Java序列化避坑指南:明确这4种场景,再也不盲目实现Serializable
java·序列化
bugcome_com6 小时前
深入了解 C# 编程环境及其开发工具
c#
wfserial8 小时前
c#使用微软自带speech选择男声仍然是女声的一种原因
microsoft·c#·speech
阔皮大师9 小时前
INote轻量文本编辑器
java·javascript·python·c#
kylezhao201910 小时前
C# 中的 SOLID 五大设计原则
开发语言·c#
啦啦啦_999911 小时前
Redis-5-doFormatAsync()方法
数据库·redis·c#
Porco.w11 小时前
C#与三菱PLC FX5U通信
网络·c#
E_ICEBLUE13 小时前
PPT 批量转图片:在 Web 预览中实现翻页效果(C#/VB.NET)
c#·powerpoint·svg
JQLvopkk15 小时前
C# 轻量级工业温湿度监控系统(含数据库与源码)
开发语言·数据库·c#