【问题标题】:Json.NET case-sensitive deserializationJson.NET 区分大小写的反序列化
【发布时间】:2016-04-06 16:57:20
【问题描述】:

是否有反序列化选项可以使用Json.NET 执行区分大小写反序列化?

建议:

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}

从以下位置反序列化时必须失败:

{
  "email": "james@example.com",
  "active": true,
  "createdDate": "2013-01-20T00:00:00Z",
  "roles": [
    "User",
    "Admin"
  ]
}

【问题讨论】:

  • 为什么要失败?在变量名中混合大小写会导致几个月后的维护噩梦

标签: c# json.net deserialization


【解决方案1】:

不幸的是,不太可能。尝试区分大小写然后不区分大小写似乎是硬编码的。

/// <summary>
/// Gets the closest matching <see cref="JsonProperty"/> object.
/// First attempts to get an exact case match of propertyName and then
/// a case insensitive match.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns>A matching property if found.</returns>
public JsonProperty GetClosestMatchProperty(string propertyName)
{
    JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
    if (property == null)
    {
        property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
    }

    return property;
}

JsonPropertyCollection

这是由内部阅读器调用的,因此没有简单的开关可以翻转。这应该是可能的,但您必须自己编写转换器来拒绝不区分大小写的匹配。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
相关资源
最近更新 更多