【问题标题】:Read JSON property name from JsonContract从 JsonContract 读取 JSON 属性名称
【发布时间】:2015-12-03 11:07:18
【问题描述】:

我有一个序列化为 JSON 的 DTO。我需要知道属性的名称,因为它将出现在 JSON 中。我有合适的IContractResolver,但我不确定如何从这个到最终的属性名称。

我用过GetResolvedPropertyName,这是一个开始但不是结束。例如,因为它需要一个字符串作为参数,所以它不能查找例如JsonPropertyAttribute 在物业上。在其他情况下,它可能无法完成全部工作。

鉴于我有PropertyInfo 和ContractResolver,我如何获得最终的属性名称?

【问题讨论】:

    标签: c# .net json json.net


    【解决方案1】:

    我不确定我是否理解为什么您需要这样做,但是,假设您的 IContractResolver 派生自 DefaultContractResolver,您可以获得如下属性名称:

    JsonObjectContract contract = (JsonObjectContract)resolver.ResolveContract(typeof(DTO));
    var dict = contract.Properties.ToDictionary(p => p.UnderlyingName, p => p.PropertyName);
    
    Console.WriteLine("Serialized property names will be: ");
    foreach (var kvp in dict)
    {
        Console.WriteLine(kvp.Key + " => " + kvp.Value);
    }
    

    小提琴:https://dotnetfiddle.net/RnwnRc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      相关资源
      最近更新 更多