using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
/// JsonObject [email protected]
namespace JsonObject
{
public enum JsonItemType
{
String,
Array,
Integer,
Node
}
public sealed class Json
{
#region -- Private Fields --
private IList<JsonItem> _col;
private int _deep = 0;
private Json _parent;
#endregion
#region -- Methods --
public Json()
{
this._col = new List<JsonItem>();
}
public void Add(string key, string value)
{
if (key == null || key == "" || value == null) throw new ArgumentException("键值不能为空,参数不能为null");
JsonItem si = new JsonItem();
si.ItemType = JsonItemType.String;
si.Key = key;
si.Value = value;
this._col.Add(si);
}
public void Add(string key, int value)
{
if (key == null || key == "") throw new ArgumentException("键值不能为空,参数不能为null");
JsonItem si = new JsonItem();
si.ItemType = JsonItemType.Integer;
si.Key = key;
si.Value = value;
this._col.Add(si);
}
public void Add(string key, IList<object> value)
{
if (key == null || key == "" || value == null) throw new ArgumentException("键值不能为空,参数不能为null");
JsonItem si = new JsonItem();
si.ItemType = JsonItemType.Array;
si.Key = key;
si.Value = value;
this._col.Add(si);
}
public void Add(string key, Json value)
{
if (key == null || key == "" || value == null) throw new ArgumentException("键值不能为空,参数不能为null");
JsonItem si = new JsonItem();
si.ItemType = JsonItemType.Node;
si.Key = key;
si.Value = value;
this._col.Add(si);
}
public override string ToString()
{
return new JsonConvert.Writer(this).ToString();
}
public static Json Parse(string jsonString)
{
return new JsonConvert.Reader(jsonString).ToJson();
}
#endregion
#region -- Properties --
public int Length
{
get { return this._col.Count; }
}
public Jszn this[string key]
{
get
{
foreach (JsonItem si in this._col)
{
if (si.Key == key)
{
return new Jszn(si);
}
}
throw new ArgumentException("没有找到Key为 " + key + " 的数据序列");
}
}
internal JsonItem this[int index]
{
get
{
return (JsonItem)this._col[index];
}
}
public int Deep
{
get { return this._deep; }
set { this._deep = value; }
}
public Json Parent
{
get { return this._parent; }
set { this._parent = value; }
}
#endregion
}
public sealed class Jszn
{
#region -- Private Fields --
JsonItem _item;
#endregion
#region -- Method --
public Jszn(JsonItem item)
{
this._item = item;
}
public override string ToString()
{
return this._item.Value.ToString();
}
public int ToInt()
{
if (this._item.ItemType == JsonItemType.Integer)
{
return Convert.ToInt32(this._item.Value);
}
else
{
throw new ArgumentOutOfRangeException("该返回数据类型不应为数字整型 Integer");
}
}
public string[] ToArray()
{
if (this._item.ItemType == JsonItemType.Array)
{
return (string[])this._item.Value;
}
else
{
throw new ArgumentOutOfRangeException("该返回数据类型不应为数组型 Array");
}
}
#endregion
#region -- Properties --
public Jszn this[string key]
{
get
{
C# JsonObject Json格式与Json对象相互转换
最新推荐文章于 2024-02-29 16:40:44 发布