json 和对象之间的转换
print?/// <summary>
/// List转成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonName"></param>
/// <param name="list"></param>
/// <returns></returns>
public static string ListToJson<T>(IList<T> list, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName))
jsonName = list[0].GetType().Name;
Json.Append("{\"" + jsonName + "\":[");
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = 0; j < pi.Length; j++)
{
Type type = pi[j].GetValue(list[i], null).GetType();
Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < list.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
/// <summary>
/// List转成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static string ListToJson<T>(IList<T> list)
{
object obj = list[0];
return ListToJson<T>(list, obj.GetType().Name);
}
/// <summary>
/// 对象转换为Json字符串
/// </summary>
/// <param name="jsonObject">对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(object jsonObject)
{
try
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("{");
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
for (int i = 0; i < propertyInfo.Length; i++)
{
object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
if (objectValue == null)
{
continue;
}
StringBuilder value = new StringBuilder();
if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
{
value.Append("\"" + objectValue.ToString() + "\"");
}
else if (objectValue is string)
{
value.Append("\"" + objectValue.ToString() + "\"");
}
else if (objectValue is IEnumerable)
{
value.Append(ToJson((IEnumerable)objectValue));
}
else
{
value.Append("\"" + objectValue.ToString() + "\"");
}
jsonString.Append("\"" + propertyInfo[i].Name + "\":" + value + ","); ; <
补充:web前端 , JavaScript ,