【问题标题】:How to assign JsonProperty attribute to properties of classes inside DLL using Json.Net?如何使用 Json.Net 将 JsonProperty 属性分配给 DLL 内的类的属性?
【发布时间】:2015-09-01 04:28:16
【问题描述】:

我在 DLL 中有一个类,它没有用 DataContract, JsonProperty 等标记。现在我想将该类的实例序列化为 JSON 对象,缩短 C# 属性名称

例如,类是:

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

我想知道是否可以在 C# 名称和 json 名称之间创建映射。我不能直接添加DataContract, JsonProperty 属性,如下所示。有什么解决办法吗?

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

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

【问题讨论】:

标签: c# json json.net datacontract


【解决方案1】:

您可以使用成员覆盖属性的字典创建自己的自定义 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
    }
}

【讨论】:

    【解决方案2】:

    这绝对是一种解决方法,但您可能需要考虑一下。如果类不是密封的,你可以继承它,覆盖它的属性(那些你想改变的),然后装饰它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多