栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在C#中覆盖Json属性名称

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在C#中覆盖Json属性名称

您必须重写

DefaultContractResolver
并实现自己的机制来提供
PropertyName
(以JSON格式)。我将提供完整的示例代码,以显示生成的运行时的反序列化和序列化
PropertyName
。当前,它将
Test
字段修改为
Test5
(在所有模型中)。您应该实现自己的机制(使用属性,保留名称,表等)。

class Program{    static void Main(string[] args)    {        var customer = new Customer() {Email = "asd@asd.com", Test = "asdasd"};        var a = Serialize(customer, false);        var b = Serialize(customer, true);        Console.WriteLine(a);        Console.WriteLine(b);        var desA = Deserialize<Customer>(a, false);        var desB = Deserialize<Customer>(b, true);        Console.WriteLine("TestA: {0}", desA.Test);        Console.WriteLine("TestB: {0}", desB.Test);    }    static string Serialize(object obj, bool newNames)    {        JsonSerializerSettings settings = new JsonSerializerSettings();        settings.Formatting = Formatting.Indented;        if (newNames)        { settings.ContractResolver = new CustomNamesContractResolver();        }        return JsonConvert.SerializeObject(obj, settings);    }    static T Deserialize<T>(string text, bool newNames)    {        JsonSerializerSettings settings = new JsonSerializerSettings();        settings.Formatting = Formatting.Indented;        if (newNames)        { settings.ContractResolver = new CustomNamesContractResolver();        }        return JsonConvert.DeserializeObject<T>(text, settings);    }}class CustomNamesContractResolver : DefaultContractResolver{    protected override IList<JsonProperty> CreateProperties(System.Type type, MemberSerialization memberSerialization)    {        // Let the base class create all the JsonProperties         // using the short names        IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);        // Now inspect each property and replace the         // short name with the real property name        foreach (JsonProperty prop in list)        { if (prop.UnderlyingName == "Test") //change this to your implementation!     prop.PropertyName = "Test" + 5;        }        return list;    }}public class Customer{    [JsonProperty(PropertyName = "email")]    public string Email { get; set; }    public string Test { get; set; }}

输出:

{  "email": "asd@asd.com",  "Test": "asdasd"}{  "email": "asd@asd.com",  "Test5": "asdasd"}TestA: asdasdTestB: asdasd

如您所见,按预期,当我们使用

Serialize(..., false)
-字段名称为时,
Test
以及当我们使用
Serialize(...,true)
-字段名称
Test5
为时。这也适用于反序列化。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636684.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号