system.text.json 搜索获取节点值

搜索Json节点值

public static class JsonStringExtensions
{
    public static bool TryGetNestValueByJsonKey(this string jsonString, stringkey, out string res)
    {
        res = string.Empty;
        try
        {
            var arr = key.Split('.');
            using (JsonDocument document = JsonDocument.Parse(jsonString))
            {
                var element = document.RootElement;
                int i = 0;
                for (; i < arr.Length; i++)
                {
                    switch (element.ValueKind)
                    {
                        case JsonValueKind.String:
                            var subKey = string.Join(
                                ".", SubArray(arr, i, arr.Length -     i));
                            
                            return TryGetNestValueByJsonKey(
                                element.GetString(), subKey,    out res);
                            
                        case JsonValueKind.Object 
                            when !element.TryGetProperty(arr[i],  out element):
                            return false;
                    }
                }
                if (i != arr.Length) return false;
                res = element.GetString();
                return true;
            }
        }
        catch
        {
            return false;
        }
    }

    public static T[] SubArray<T>(T[] array, int startIndex, int length)
    {
        T[] result = new T[length];
        Array.Copy(array, startIndex, result, 0, length);
        return result;
    }
}

使用方式:

// keyName:body.msg.out_order_no

if (!string.IsNullOrWhiteSpace(parameters) && parameters.TryGetNestValueByJsonKey(keyName, out string value))
{
      //查到了
}
posted @ 2024-04-01 20:43  李修乐  阅读(83)  评论(0)    收藏  举报