需要引用程序集:
System.Net.Http
System.Web
System.Web.Extensions
Code:
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Web; using System.Web.Script.Serialization; namespace Common.Utils { public class ToJsonTran { public static HttpResponseMessage ToJson(Object obj) { String str; if (obj is String || obj is Char) { str = obj.ToString(); } else { JavaScriptSerializer serializer = new JavaScriptSerializer(); str = serializer.Serialize(obj); } HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; return result; } } }
将对象转为json,加入到HttpResponseMessage中
原文:http://www.cnblogs.com/xsj1989/p/5282739.html