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

在Json.Net中序列化属性,但不反序列化属性

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

在Json.Net中序列化属性,但不反序列化属性

最简单的方法是将real属性标记为,

[JsonIgnore]
并创建一个get-
only代理属性:

    /// <summary>    /// Gets or sets the country pre, and province or state pre delimited by a vertical pipe: <c>US|MI</c>    /// </summary>    [JsonIgnore]    public string CountryProvinceState    {        get        { return string.Format("{0}|{1}", this.CountryCode, this.ProvinceState);        }        set        { if (!string.IsNullOrWhiteSpace(value) && value.Contains("|")) {     string[] valueParts = value.Split('|');     if (valueParts.Length == 2)     {         this.CountryCode = valueParts[0];         this.ProvinceState = valueParts[1];     } }        }    }    [JsonProperty("countryProvinceState")]    string ReadCountryProvinceState    {        get { return CountryProvinceState; }     }

如果需要,代理属性可以是私有的。

更新资料

如果必须对许多类中的许多属性执行此操作,则可能会更容易创建自己的

ContractResolver
检查自定义属性的属性。如果找到,则该属性将表示该属性为仅获取:

[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = false)]public class GetonlyJsonPropertyAttribute : Attribute{}public class GetonlyContractResolver : DefaultContractResolver{    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)    {        var property = base.CreateProperty(member, memberSerialization);        if (property != null && property.Writable)        { var attributes = property.AttributeProvider.GetAttributes(typeof(GetOnlyJsonPropertyAttribute), true); if (attributes != null && attributes.Count > 0)     property.Writable = false;        }        return property;    }}

然后像这样使用它:

[JsonProperty("countryProvinceState")][GetOnlyJsonProperty]public string CountryProvinceState { get; set; }

然后:

        var settings = new JsonSerializerSettings { ContractResolver = new GetonlyContractResolver() };        var address = JsonConvert.DeserializeObject<Address>(jsonString, settings);


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

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

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