namespace etoy { class KsonObject { string _kson; Dictionary _stringValues; Dictionary _objects; Dictionary> _arrayObjects; List _tempValues; bool _is_object; bool _is_array; int _field_count; public Dictionary StringValues => _stringValues; public Dictionary KsonObjects => _objects; public Dictionary> ArrayObjects => _arrayObjects; public string RawKson => _kson; public bool IsObject => _is_object; public bool IsArray => _is_array; public int FieldCount => _field_count; public KsonObject(string kson) { _kson = kson; _stringValues = new Dictionary(); _objects = new Dictionary(); _arrayObjects = new Dictionary>(); _tempValues = new List(); _is_object = _kson[0] == '{' && _kson[^1] == '}'; _is_array = _kson[0] == '[' && _kson[^1] == ']'; ParseValues(this); _tempValues.Clear(); } void ParseValues(KsonObject obj) { var values = GetStringValues(obj._kson); _field_count = values.Length; for (int i = 0, length = values.Length; i < length; i++) { var value = values[i]; bool is_object = value[0] == '{' && value[^1] == '}'; bool is_array = value[0] == '[' && value[^1] == ']'; if (is_object) { if (obj._is_array) { if (!obj._arrayObjects.TryGetValue(i, out var collection)) { collection = new List(); obj._arrayObjects[i] = collection; } collection.Add(new KsonObject(value)); } if (obj.IsObject) obj._objects.Add(i, new KsonObject(value)); } else if (is_array) { var objValues = GetStringValues(value); List list = new List(); foreach (var objValue in objValues) list.Add(new KsonObject(objValue)); if (obj._is_array) { throw new System.Exception("不支持多维数组"); } if (obj._is_object) obj._arrayObjects.Add(i, list); } else { obj._stringValues.Add(i, value); } } } string[] GetStringValues(string kson) { if (string.IsNullOrEmpty(kson)) return new string[] { }; if (kson.Length > 1) kson = kson[1..(kson.Length - 1)]; _tempValues.Clear(); int right, left = 0, indent = 0; for (int i = 0, length = kson.Length; i < length; i++) { char c = kson[i]; if (c == '{' || c == '[') indent++; if (c == '}' || c == ']') indent--; if (indent != 0) continue; if (c == ',') { right = i; string value = kson[left..right]; _tempValues.Add(value); left = i + 1; } if (i == length - 1) { string value = kson[left..length]; _tempValues.Add(value); } } return _tempValues.ToArray(); } } }