You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让JsonElement.GetProperty()支持大小写不敏感?

解决JsonElement.GetProperty忽略大小写的问题

针对JSON属性大小写不统一的情况,最直接的解决方案是给JsonElement编写一个忽略大小写的扩展方法,通过遍历对象属性进行匹配。以下是具体实现:

实现扩展方法

public static class JsonElementExtensions
{
    public static JsonElement GetPropertyIgnoreCase(this JsonElement element, string propertyName)
    {
        if (element.ValueKind != JsonValueKind.Object)
            throw new InvalidOperationException("操作仅适用于JSON对象类型元素");

        foreach (var property in element.EnumerateObject())
        {
            if (string.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase))
            {
                return property.Value;
            }
        }

        throw new KeyNotFoundException($"未找到属性 '{propertyName}'");
    }
}

使用方式

直接替换原有GetProperty调用即可,不管目标属性是camelCase还是PascalCase,都能正常匹配:

var jsonStr = "{\"UserName\":\"张三\",\"email\":\"zhangsan@example.com\"}";
using var doc = JsonDocument.Parse(jsonStr);
var root = doc.RootElement;

// 匹配PascalCase的UserName
var userName = root.GetPropertyIgnoreCase("username").GetString();
// 匹配camelCase的email
var email = root.GetPropertyIgnoreCase("Email").GetString();

注意事项

  • 若JSON对象中存在多个仅大小写不同的重复属性(比如同时存在UserName和username),方法会返回第一个匹配到的属性(JSON标准不允许重复属性,但部分解析器可能兼容);
  • 扩展方法抛出的异常类型和原生GetProperty保持一致,无需修改原有代码的异常处理逻辑;
  • 由于需要遍历属性,极大型JSON对象的匹配性能会略低于原生大小写敏感匹配,但大部分业务场景下可忽略该差异。

内容的提问来源于stack exchange,提问作者Sharif Rezvani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 23:29:53