110,536
社区成员
发帖
与我相关
我的任务
分享
namespace EB.Common
{
public class A
{
private string _id;
private string _name;
private string _code;
IList<EB.Common.B> _detail;
public string ID
{
set { _id = value; }
get { return _id; }
}
public string Name
{
set { _name = value; }
get { return _name; }
}
public string Code
{
set { _code = value; }
get { return _code; }
}
public IList<EB.Common.B> Detail
{
set { _detail = value; }
get { return _detail; }
}
}
}
namespace EB.Common
{
public class B
{
private string _id;
private int _num;
private string _type;
public string ID
{
set { _id = value; }
get { return _id; }
}
public int Num
{
set { _num = value; }
get { return _num; }
}
public string Type
{
set { _type = value; }
get { return _type; }
}
}
}
IList<EB.Common.A>
,现在要给前台返回JSON格式的数据,从网上找了一个通过反射和泛型把IList转换为JSON字符串,转换代码如下:public static string EntityToJson(IList<T> items)
{
StringBuilder Json = new StringBuilder();
Json.Append("[");
if (items.Count > 0)
{
for (int i = 0; i < items.Count; i++)
{
T obj = Activator.CreateInstance<T>();
Type type = obj.GetType();
PropertyInfo[] pis = type.GetProperties();
Json.Append("{");
for (int j = 0; j < pis.Length; j++)
{
Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(items[i], null) + "\"");
if (j < pis.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < items.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]");
return Json.ToString();
}
//IList<EB.Common.A> rlist = 从数据库获取的数据结果集
string jsonStr = EB.Common.Convertor.IListToJson.JsonHelper<EB.Common.A>.EntityToJson(rlist);
public static string EntityToJson(IList<T> items)
{
StringBuilder Json = new StringBuilder();
Json.Append("[");
if (items.Count > 0)
{
for (int i = 0; i < items.Count; i++)
{
T obj = Activator.CreateInstance<T>();
Type type = obj.GetType();
PropertyInfo[] pis = type.GetProperties();
Json.Append("{");
for (int j = 0; j < pis.Length; j++)
{
//这里判断类的成员变量是否是IList集合类型
if (pis[j].PropertyType.Name == "IList`1" && pis[j].PropertyType.Namespace == "System.Collections.Generic")
{
//这里如何实现递归调用生成第二层json?
//EntityToJson(IList < T > items);
}
else
{
Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(items[i], null) + "\"");
if (j < pis.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < items.Count - 1)
{
Json.Append(",");
}
}
}
}
Json.Append("]");
return Json.ToString();
}
/// <summary>
/// 转换成json
/// </summary>
/// <typeparam name="T">结果数据类型</typeparam>
/// <param name="t">结果数据</param>
/// <returns>json数据</returns>
public static string ConvertToJson<T>(ResultModel<T> t)
{
JavaScriptObject ReturnResult = new JavaScriptObject();
JavaScriptObject ResultMessage = new JavaScriptObject();
ResultMessage["code"] = t.code;
ResultMessage["msg"] = t.msg;
if (t.data != null)
{
ResultMessage["data"] = t.data;
}
ReturnResult["result"] = ResultMessage;
return JavaScriptConvert.SerializeObject(ReturnResult);
}
/// <summary>
/// 泛型结果集模型
/// yws
/// 2016年3月31日13:14:51
/// </summary>
[XmlRoot("result")]
public class ResultBase
{
/// <summary>
/// 结果
/// </summary>
public string code;
/// <summary>
/// 提示
/// </summary>
public string msg;
}
/// <summary>
/// 泛型结果集模型
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
[XmlRoot("result")]
public class ResultModel<T> : ResultBase
{
/// <summary>
/// 结果集
/// </summary>
public T data;
/// <summary>
/// 默认构造函数
/// </summary>
public ResultModel()
{ }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="t">内部数据</param>
public ResultModel(T t)
{
data = t;
}
}
using System.Web.Script.Serialization;//需要添加引用System.Web.Extensions
使用代码:
A aClass = new A()
{
ID = "1",
Name = "1A",
Code = "1ACode",
Detail = new List<B> {
new B() { ID= "1", Num=1,Type="1Type" },
new B() { ID= "2", Num=2,Type="3Type" },
},
DateField = new DateTime(2017, 01, 01, 8, 30, 30, 500) //为了说明另外增加的字段
};
//序列化
JavaScriptSerializer jss = new JavaScriptSerializer();
string jsonStr = jss.Serialize(aClass);
//反序列化(动态类型)
dynamic aDynamic = jss.Deserialize<dynamic>(jsonStr);
dynamic bList = aDynamic["Detail"];
string B0ID1 = bList[0]["ID"] + "";//结果:1
string B0ID2 = aDynamic["Detail"][1]["ID"] + "";//结果:2
string Name = (string)aDynamic["Name"];//结果:1A
//注意如果序列化时对象时间没有时区信息,那么范序列化会变成0时区(比北京时间少8小时)
string DateFieldString = ((DateTime)aDynamic["DateField"]).ToString("yyyy-MM-dd HH:mm:ss.fff");//结果:2017-01-01 00:30:30:5000
//注意如果序列化时对象时间没有时区信息,如果需要得到当前时区正确时间,需要ToLocalTime
string DateFieldLocalString = ((DateTime)aDynamic["DateField"]).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss.fff");////结果:2017-01-01 08:30:30:5000
//反序列化为对应类型
A aClass2 = jss.Deserialize<A>(jsonStr);
IList<B> bList2 = aClass2.Detail;
string B0ID3 = bList2[0].ID;
string B0ID4 = aClass2.Detail[1].ID;
string Name2 = aClass2.Name;
DateTime DateField2 = aClass2.DateField.ToLocalTime();//结果:当前时间(带时区)