#region sta+ 对于字典数据生成json字符串
/// <summary>
/// 对于字典数据生成json字符串
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetJson(Dictionary<string, string> value)
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
foreach (var item in value.Keys)
{
sb.Append("\"" + item + "\":\"" + value[item] + "\"");
sb.Append(",");
}
sb.Remove(sb.Length - 1, 1).Append("}");
return sb.ToString();
}
#endregion
#region sta+ 集合生成json
/// <summary>
/// 集合生成json
/// </summary>
/// <returns></returns>
public static string ListObjectToJson<T>(List<T> list)
{
StringBuilder sb = new StringBuilder();
if (list == null) { return "[]"; }
if (list.Count > 0)
{
Type type = list[1].GetType();
if (list.Count == 1)
{
sb.Append(ObjectToJson<T>(list[0]));
}
else
{
sb.Append("[");
foreach (T item in list)
{
sb.Append(ObjectToJson<T>(item));
sb.Append(",");
}
sb.Remove(sb.Length - 1, 1).Append("]");
}
}
else
{
sb.Append("[]");
}
return sb.ToString();
}
#endregion
#region sta+ 生成对象的json格式
/// <summary>
/// 生成对象的json格式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tt"></param>
/// <returns></returns>
public static string ObjectToJson<T>(T tt)
{
StringBuilder sb = new StringBuilder();
Type t = tt.GetType();
PropertyInfo[] proterties = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);
if (proterties.Length <= 0)
{
return default(string);
}
sb.Append("{");
foreach (var item in proterties) //属性值获取
{
string name = item.Name;
var value = item.GetValue(tt, null);
sb.Append("\"" + name + "\":");
//是否是值类型或者是string类型
if (item.PropertyType.IsValueType || item.PropertyType.Name.ToLowerInvariant().StartsWith("string"))
{
if ((value is DateTime) && Convert.ToDateTime(value).Year == 1)
{
sb.Append("\"\"");
}
else
{
sb.Append("\"" + value + "\"");
}
sb.Append(",");
}
else
{
//是泛型类(暂不能判断是集合类)未实现
if (item.PropertyType.IsClass && item.PropertyType.IsGenericType)
{
List<T> list = value as List<T>;
sb.Append(ListObjectToJson<T>(list));
// string typename = item.PropertyType.GetGenericArguments()[0].Name;
//ListType(value, typename,ref sb);
}//如果是数组
else if (item.PropertyType.IsClass && item.PropertyType.IsArray)
{
sb.Append("[");
foreach (var i in (value as Array))
{
sb.Append(i);
sb.Append(",");
}
sb.Remove(sb.Length - 1, 1).Append("]");
}
else
{
ObjectToJson(value);
}
sb.Append(",");
}
}
sb.Remove(sb.Length - 1, 1).Append("}");
return sb.ToString();
}
#endregion
将对象转换为json字符串
最新推荐文章于 2024-04-12 15:16:48 发布