序列化属性,但不要Json.Net反序列化属性 [英] Serialize Property, but Do Not Deserialize Property in Json.Net

查看:153
本文介绍了序列化属性,但不要Json.Net反序列化属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我已经找到了很多办法,而$ P $来自序列化,我在寻找相反的行为pventing他们反序列化特定属性。

While I've found plenty of approaches to deserializing specific properties while preventing them from serializing, I'm looking for the opposite behavior.

我发现很多询问逆问题:

I've found plenty of questions asking the inverse:

<一个href=\"http://stackoverflow.com/questions/11564091/making-a-property-deserialize-but-not-serialize-with-json-net\">Making属性反序列化,但不与json.net

<一个href=\"http://stackoverflow.com/questions/20585810/can-i-instruct-json-net-to-deserialize-but-not-serialize-specific-properties\">Can我指示Json.NET反序列化,但不能序列化,特定的属性?

<一个href=\"http://stackoverflow.com/questions/7681538/json-net-use-jsonignoreattribute-only-on-serialization-but-not-when-deserialz\">JSON.Net - 使用JsonIgnoreAttribute只在序列化(但不是deserialzing时)

我如何序列化一个特定的属性,但是prevent从反序列化回POCO?有没有我可以用它来装点特定属性的属性?

How can I serialize a specific property, but prevent it from deserializing back to the POCO? Is there an attribute I can use to decorate the specific property?

基本上我正在寻找一个相当于ShouldSerialize *反序列化的方法。

Basically I'm looking for an equivalent to the ShouldSerialize* methods for deserialization.

我知道我可以写一个自定义转换器,但是,似乎是矫枉过正这一点。

I know I can write a custom converter, but that seems like overkill for this.

编辑:

这里有一个小更多的上下文。这背后的原因是我班的样子:

Here's a little more context. The reason behind this is my class looks like:

public class Address : IAddress
{
    /// <summary>
    /// Gets or sets the two character country code
    /// </summary>
    [JsonProperty("countryCode")]
    [Required]
    public string CountryCode { get; set; }

    /// <summary>
    /// Gets or sets the country code, and province or state code delimited by a vertical pipe: <c>US|MI</c>
    /// </summary>
    [JsonProperty("countryProvinceState")]
    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("provinceState")]
    [Required]
    public string ProvinceState { get; set; }
}

我需要请求的 CountryProvinceState 属性,但我不希望它反序列化回并触发二​​传手逻辑。

I need the CountryProvinceState property for the request, but I don't want it to deserialize back and trigger the setter logic.

推荐答案

简单的方法是,以纪念不动产作为的 [JsonIgnore] ,并创建一个只能获得代理属性:

Simplest method would be to mark the real property as [JsonIgnore] and create a get-only proxy property:

    /// <summary>
    /// Gets or sets the country code, and province or state code 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; } 
    }

如果您希望代理属性可以是私有的。

The proxy property can be private if you desire.

更新

如果你有大量的类来做到这一点为许多特性,它可能是更容易地创建自己的<一个href=\"http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_DefaultContractResolver.htm\"相对=nofollow> ContractResolver 来检查自定义属性。如果找到,则该属性将标志着该属性得到只:

If you have to do this for lots of properties in lots of classes, it might be easier to create your own ContractResolver that checks for a custom attribute. If found, the attribute would signal that the property is get-only:

[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);

这篇关于序列化属性,但不要Json.Net反序列化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆