asp.net json,对象,字符串的相互转换

//object 转json格式字符串
public static string ObjectToJsonString(this object obj)

{

return JsonConvert.SerializeObject(obj).Replace("\r\n", "");

}

//json字符串转实体
public static T JsonToObject<T>(this string json)

{

return JsonConvert.DeserializeObject<T>(json);

}

//对象转JSON
public static string ObjToJson(object obj)
{
StringBuilder sb = new StringBuilder();
JavaScriptSerializer jserializer = new JavaScriptSerializer();
jserializer.MaxJsonLength = int.MaxValue;
jserializer.Serialize(obj, sb);
return sb.ToString().Replace("/u0026", "&");
}

//json转对象
public static T JsonToObj<T>(string json)
{
JavaScriptSerializer jserializer = new JavaScriptSerializer();
jserializer.MaxJsonLength = int.MaxValue;
if (string.IsNullOrEmpty(json)) json = "{}";
T obj = jserializer.Deserialize<T>(json);
return obj;
}

上一篇:WCF技术剖析之三十:一个很有用的WCF调用编程技巧[下篇]


下一篇:【weiphp微信开发教程】留言板插件开发详解