c#生成json类
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization;
namespace json
{
/**//// <summary>
/// JSONHelper 的摘要说明
/// </summary>
public class Json
{
public bool success = true;
public string error = string.Empty;
public string singleInfo = string.Empty;
protected System.Collections.ArrayList arrData;
protected System.Collections.ArrayList arrDataItem;
public Json()
{
arrData = new ArrayList();
arrDataItem = new ArrayList();
}
//重置,每次新生成一个json对象时必须执行该方法
public void Reset()
{
success = true;
error = string.Empty;
singleInfo = string.Empty;
arrData.Clear();
arrDataItem.Clear();
}
/// <summary>
/// 添加data数组中一个元素(js对象)的一个名值对,例如
///对于一个数组元素:{userName:"supNate",userId:"1"}
///需执行两次AddItem:
///AddItem("userName","supNate");
///AddItem("userId","1");
///最后执行
///ItemOk();
//表示数组元素添加完毕,底下的AddItem表示另一个数组元素的开始
/// </summary>
/// <param name="name"></param>
/// <param name="_value"></param>
public void AddItem(string name, string _value)
{
arrDataItem.Add(name);
arrDataItem.Add(_value.Replace("\"", "\\\""));
}
//一个数组元素添加完毕(data数组)
public void ItemOk()
{
arrData.Add(arrDataItem);
arrDataItem = new ArrayList();
}
//得到返回的json代码
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
sb.Append("success:" + success.ToString() + ",");
sb.Append("error:\"" + error + "\",");
sb.Append("singleInfo:\"" + singleInfo + "\",");
sb.Append("data:[");
for (int i = 0; i < arrData.Count; i++)
{
ArrayList arr = (ArrayList)arrData[i];
sb.Append("{");
for (int j = 0; j < arr.Count; j += 2)
{
if (j == arr.Count) break;
sb.Append((string)arr[j]);
sb.Append(":");
sb.Append("\"");
sb.Append((string)arr[j + 1]);
sb.Append("\"");
if (j < arr.Count - 2) sb.Append(",");
}
sb.Append("}");
if (i < arrData.Count - 1) sb.Append(",");
}
sb.Append("]");
sb.Append("}");
return sb.ToString();
}
}
}