Json.NET区分大小写的反序列化

时间:2016-01-02 16:36:01

标签: c# json.net deserialization

是否可以指定一些反序列化选项以使用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"
  ]
}

1 个答案:

答案 0 :(得分:14)

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

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

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