ln.json/JSONObject.cs

94 lines
2.4 KiB
C#
Raw Permalink Normal View History

2017-10-26 16:41:14 +02:00
using System;
using System.Text;
using System.Collections.Generic;
2020-11-18 00:36:18 +01:00
using ln.collections;
2019-08-19 14:13:59 +02:00
using ln.json.mapping;
2017-10-26 16:41:14 +02:00
2019-08-07 23:02:00 +02:00
namespace ln.json
2017-10-26 16:41:14 +02:00
{
2019-08-07 23:02:00 +02:00
public class JSONObject : JSONValue
2017-10-26 16:41:14 +02:00
{
2019-08-07 23:02:00 +02:00
public IEnumerable<string> Keys => values.Keys;
2017-11-03 13:13:09 +01:00
2019-08-07 23:02:00 +02:00
public override IEnumerable<JSONValue> Children => values.Values;
public override bool HasChildren => true;
2017-11-03 13:13:09 +01:00
2019-08-08 00:34:16 +02:00
public int Count => values.Count;
2019-08-07 23:02:00 +02:00
BTree<string, JSONValue> values = new BTree<string, JSONValue>();
2017-10-26 16:41:14 +02:00
2019-08-07 23:02:00 +02:00
public JSONObject()
:base(JSONValueType.OBJECT){}
public override JSONValue this[string property]
{
get => values[property];
set => values[property] = value;
}
2019-08-19 14:13:59 +02:00
public JSONObject Add(string propertyName, JSONValue value)
2019-08-07 23:02:00 +02:00
{
values[propertyName] = value;
return this;
}
2019-08-19 14:13:59 +02:00
public JSONObject Add(string propertyName, object value)
{
2020-11-18 00:36:18 +01:00
if (JSONMapper.DefaultMapper.Serialize(value,out JSONValue jsonValue))
{
values[propertyName] = jsonValue;
}
2019-08-19 14:13:59 +02:00
return this;
}
2019-08-07 23:02:00 +02:00
2019-08-08 00:34:16 +02:00
public bool ContainsKey(string key)
{
return values.ContainsKey(key);
}
2019-08-19 14:13:59 +02:00
public T ToObject<T>()
{
2020-11-18 00:36:18 +01:00
if (JSONMapper.DefaultMapper.Deserialize(this, typeof(T), out object o))
{
return (T)o;
}
throw new NotSupportedException();
2019-08-19 14:13:59 +02:00
}
2019-08-07 23:02:00 +02:00
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();
}
2019-08-19 14:13:59 +02:00
public static JSONObject From(object value)
{
2020-11-18 00:36:18 +01:00
if (JSONMapper.DefaultMapper.Serialize(value, out JSONValue json))
{
return (JSONObject)json;
}
throw new NotSupportedException();
2019-08-19 14:13:59 +02:00
}
2019-08-07 23:02:00 +02:00
}
2019-08-19 14:13:59 +02:00
2017-10-26 16:41:14 +02:00
}