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

本文关键字:反序列化 大小写 NET Json | 更新日期: 2023-09-27 18:28:40

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

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

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

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

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