搜索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))
{
//查到了
}
标签:arr,return,string,text,system,element,json,res,out
From: https://www.cnblogs.com/pw55b/p/18109326