gpt4 book ai didi

c# - 如何使用 Json.Net 将 JsonProperty 属性分配给 DLL 中类的属性?

转载 作者:行者123 更新时间:2023-11-30 12:42:55 27 4
gpt4 key购买 nike

我在 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
}
}

关于c# - 如何使用 Json.Net 将 JsonProperty 属性分配给 DLL 中类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323545/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com