内容目录
// json => Dictionary
static Dictionary<string, string> Read(string jsonData)
{
var reader = new Utf8JsonReader(Encoding.Default.GetBytes(jsonData), _jsonReaderOptions);
var map = new Dictionary<string, string>();
BuildMap(ref reader, map);
return map;
}
// json => Dictionary
public static void BuildMap(ref Utf8JsonReader reader, Dictionary<string, string> map, string baseKey = null)
{
while (reader.Read())
{
if (reader.TokenType is JsonTokenType.StartArray) reader.Skip();
else if (reader.TokenType is JsonTokenType.EndObject) break;
else if (reader.TokenType is JsonTokenType.PropertyName)
{
var key = reader.GetString()!;
var newkey = baseKey is null ? key : $"{baseKey}.{key}";
reader.Read();
if (reader.TokenType is JsonTokenType.StartArray) reader.Skip();
else if (reader.TokenType is JsonTokenType.StartObject) BuildMap(ref reader, map, newkey);
else map[newkey] = ReadString(reader);
}
}
}
// 解析 json 字段
static string ReadString(Utf8JsonReader reader)
{
return reader.TokenType switch
{
JsonTokenType.False or JsonTokenType.True => reader.GetBoolean().ToString(),
JsonTokenType.Number => reader.GetInt32().ToString(),
JsonTokenType.String => reader.GetString() ?? "",
_ => "",
};
}
文章评论