ln.json/JSONObject.cs

89 lines
2.3 KiB
C#

using System;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Security.Cryptography;
using ln.types.btree;
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)
{
values[propertyName] = JSONMapper.DefaultMapper.ToJson(value);
return this;
}
public bool ContainsKey(string key)
{
return values.ContainsKey(key);
}
public T ToObject<T>()
{
return JSONMapper.DefaultMapper.FromJson<T>(this);
}
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(':');
if (values[kenum.Current]!=null)
sb.Append(values[kenum.Current].ToString());
else
sb.Append("null");
if (!kenum.MoveNext())
break;
sb.Append(',');
} while (true);
sb.Append('}');
return sb.ToString();
}
public static JSONObject From(object value)
{
return (JSONObject)JSONMapper.DefaultMapper.ToJson(value);
}
}
}