ln.json/ln.json/JSONObject.cs

141 lines
3.8 KiB
C#

using System;
using System.Text;
using System.Collections.Generic;
using System.Dynamic;
using ln.collections;
using ln.json.mapping;
namespace ln.json
{
public class JSONObject : JSONValue
{
public IEnumerable<string> Keys => values.Keys;
public override IEnumerable<JSONValue> Children => values.Values;
public override bool HasChildren => true;
public int Count => values.Count;
BTree<string, JSONValue> values = new BTree<string, JSONValue>();
public JSONObject()
:base(JSONValueType.OBJECT){}
public override JSONValue this[string property]
{
get => values[property];
set => values[property] = value;
}
public JSONObject Add(string propertyName, JSONValue value)
{
values[propertyName] = value;
return this;
}
public JSONObject Add(string propertyName, object value)
{
if (JSONMapper.DefaultMapper.Serialize(value,out JSONValue jsonValue))
{
values[propertyName] = jsonValue;
}
return this;
}
public void Remove(string propertyName) => values.Remove(propertyName);
public bool ContainsKey(string key)
{
return values.ContainsKey(key);
}
public bool TryGetValue(string key, out JSONValue jsonValue) => values.TryGet(key, out jsonValue);
public bool TryGetValue<OT>(string key, out OT value) where OT : JSONValue
{
if (TryGetValue(key, out JSONValue jsonValue) && (jsonValue is OT otValue))
{
value = otValue;
return true;
}
value = default;
return false;
}
public T ToObject<T>()
{
if (JSONMapper.DefaultMapper.Deserialize(this, typeof(T), out object o))
{
return (T)o;
}
throw new NotSupportedException();
}
public override JSONValue Clone()
{
JSONObject copy = new JSONObject();
foreach (var key in Keys)
copy[key] = this[key].Clone();
return copy;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('{');
IEnumerator<string> kenum = values.Keys.GetEnumerator();
if (kenum.MoveNext())
do
{
sb.Append('"');
sb.Append(kenum.Current);
sb.Append('"');
sb.Append(':');
sb.Append(values[kenum.Current].ToString());
if (!kenum.MoveNext())
break;
sb.Append(',');
} while (true);
sb.Append('}');
return sb.ToString();
}
public override bool TryGetMember(GetMemberBinder binder, out object? result)
{
if (values.TryGet(binder.Name, out JSONValue jsonValue))
{
result = jsonValue;
return true;
}
result = null;
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object? value)
{
if (value is JSONValue jsonValue)
values[binder.Name] = jsonValue;
else
values[binder.Name] = JSONMapper.DefaultMapper.ToJson(value);
return true;
}
public static JSONObject From(object value)
{
if (JSONMapper.DefaultMapper.Serialize(value, out JSONValue json))
{
return (JSONObject)json;
}
throw new NotSupportedException();
}
}
}