C# 将 JSON 转换为键值

2022年10月10日 1228点热度 0人点赞 0条评论
内容纲要

        // 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() ?? "",
                _ => "",
            };
        }

痴者工良

高级程序员劝退师

文章评论