利用JsonDocument 及递归 实现简易的Json扁平化处理
using System.Text.Json;
var str = "{\"Code\":200,\"Data\":{\"url1\":\"1111\",\"url2\":\"2222\",\"url3\":\"3333\",\"url4\":\"4444\"}}";
//扁平化数据结果
var data = new Dictionary<string, string>();
//用来记录json属性名
var pathStack = new Stack<string>();
//数据层级分割字符串
var splitChar = ".";
//转换为JsonDocument对象
using (var doc = JsonDocument.Parse(str))
{
JsonFlatten(doc.RootElement);
}
//递归实现json节点解析=>扁平化
void JsonFlatten(JsonElement element)
{
Action<dynamic> recordAction = (name) => pathStack.Push((pathStack.Count > 0 ? (pathStack.Peek() + splitChar) : string.Empty) + name);
foreach (JsonProperty property in element.EnumerateObject())
{
recordAction(property.Name);
switch (property.Value.ValueKind)
{
case JsonValueKind.Object:
JsonFlatten(property.Value);
break;
case JsonValueKind.Array:
int index = 0;
foreach (JsonElement arrayElement in property.Value.EnumerateArray())
{
recordAction(index.ToString());
JsonFlatten(arrayElement);
pathStack.Pop();
index++;
}
break;
default:
string key = pathStack.Peek();
data[key] = property.Value.ToString();
break ;
}
pathStack.Pop();
}
}