加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用Json.Net将JsonProperty属性分配给DLL内的类的属

发布时间:2020-12-15 22:19:54 所属栏目:百科 来源:网络整理
导读:我在DLL中有一个类,它没有标记DataContract,JsonProperty等.现在我想将类的实例序列化为 JSON对象,并缩短C#属性名称. 例如,该课程是: public class Foo{ public string SomeLengthyCSharpPropertyName { get; set; }} I wonder if I could create a mapping
我在DLL中有一个类,它没有标记DataContract,JsonProperty等.现在我想将类的实例序列化为 JSON对象,并缩短C#属性名称.

例如,该课程是:

public class Foo
{
    public string SomeLengthyCSharpPropertyName { get; set; }
}

I wonder if I could create a mapping between the C# names and the json names. I cannot directly add the DataContract,JsonProperty attributes like below. Is there any workaround?

[DataContract]
public class Foo
{
    [JsonProperty("s")]
    public string SomeLengthyCSharpPropertyName { get; set; }
}

我倾向于不创建另一个具有相同但JsonProperty装饰属性的类,并将属性复制到新类,然后序列化.

解决方法

您可以使用成员的覆盖属性字典创建自己的自定义 ContractResolver,然后覆盖 CreateProperty()并将覆盖应用于基类返回的 JsonProperty

public class JsonPropertyOverride
{
    public string PropertyName { get; set; }

    public bool? Ignored { get; set; }

    // Others as required from http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonPropertyAttribute.htm
    // Changing all value type properties to nullables.
}

public class OverrideContractResolver : DefaultContractResolver
{
    readonly Dictionary<MemberInfo,JsonPropertyOverride> overrides; // A private copy for thread safety.

    public OverrideContractResolver(IDictionary<MemberInfo,JsonPropertyOverride> overrides)
        : base()
    {
        if (overrides == null)
            throw new ArgumentNullException();
        this.overrides = overrides.ToDictionary(p => p.Key,p => p.Value);
    }

    protected override JsonProperty CreateProperty(MemberInfo member,MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member,memberSerialization);
        if (property != null)
        {
            JsonPropertyOverride attr;
            if (overrides.TryGetValue(member,out attr))
            {
                if (attr.PropertyName != null)
                    property.PropertyName = ResolvePropertyName(attr.PropertyName);
                if (attr.Ignored != null)
                    property.Ignored = attr.Ignored.Value;
            }
        }
        return property;
    }
}

如果您愿意,也可以从CamelCasePropertyNamesContractResolver继承.

然后使用它像:

public class Foo
{
    public string SomeLengthyCSharpPropertyName { get; set; }

    public string DefaultNotIgnored { get; set; }

    [JsonIgnore]
    public string DefaultIgnored { get; set; }
}

public class TestClass
{
    public static void Test()
    {
        var foo = new Foo { SomeLengthyCSharpPropertyName = "SomeLengthyCSharpPropertyName",DefaultIgnored = "DefaultIgnored",DefaultNotIgnored = "DefaultNotIgnored" };

        var resolver = new OverrideContractResolver(new Dictionary<MemberInfo,JsonPropertyOverride> { 
            { typeof(Foo).GetProperty("SomeLengthyCSharpPropertyName"),new JsonPropertyOverride { PropertyName = "c"  } },{ typeof(Foo).GetProperty("DefaultNotIgnored"),new JsonPropertyOverride { Ignored = true  } },{ typeof(Foo).GetProperty("DefaultIgnored"),new JsonPropertyOverride { Ignored = false  } },});
        var settings = new JsonSerializerSettings { ContractResolver = resolver };

        var json = JsonConvert.SerializeObject(foo,settings); // Outputs {"c":"SomeLengthyCSharpPropertyName","DefaultIgnored":"DefaultIgnored"}
        Debug.WriteLine(json);

        var expectedJson = @"{ ""c"": ""SomeLengthyCSharpPropertyName"",""DefaultIgnored"": ""DefaultIgnored"" }";
        var ok = JToken.DeepEquals(JToken.Parse(json),JToken.Parse(expectedJson));
        Debug.Assert(ok); // No assert

        var foo2 = JsonConvert.DeserializeObject<Foo>(json,settings);

        var ok2 = foo2.DefaultIgnored == foo.DefaultIgnored && foo2.SomeLengthyCSharpPropertyName == foo.SomeLengthyCSharpPropertyName;
        Debug.Assert(ok2); // No assert
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读