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

标签 c# json json.net datacontract

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

相关文章:

c# - JSON.net 卡在 DeserializeObject

c# - 是否可以使用 NPOI 和 C# 编辑 .xlsm 文件

c# - 如何动态定义超链接点击事件?

c# - 如何偏移实例化的 GameObject 以避免重叠(数字例如 1、10、100、1000)?

android - 用于嵌套 json 的 POJO

c# - 在 C# 中使用 Newtonsoft.Json.Linq 查询 JSON 操作日期字符串

c# - 如何防止图钉通过弹出窗口显示?

javascript - 将 JSON 数据格式化为表

json - 在 json rest web 服务中表示外键关系的标准方法

c# - json.net: DateTimeStringConverter 在 ReadJson() 中获取一个已经转换为 DateTime 的对象