要说写这个功能呢也是因为工作需要,白天呢上班写个Web页面需要ajax请求后台并将数据以Json格式传会前端,由于公司特殊性吧,不能连外网(很苦比)。所以只有等到晚上回家上网边查边写!
public class DataToJson { private static System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer(); //没问题 public static string GetJson(int state, string msg) { StringBuilder jsStr = new StringBuilder(); jsStr.Append("{"); jsStr.AppendFormat("\"State\":{0},\"Msg\":\"{1}\"", state, msg); jsStr.Append("}"); return jsStr.ToString(); } //没问题 public static string GetJson(string jsonName, object o) { StringBuilder jsStr = new StringBuilder(); jsStr.Append("{"); jsStr.AppendFormat("\"{0}\":{1}", jsonName, ser.Serialize(o)); jsStr.Append("}"); return jsStr.ToString(); } public static string GetJson(int state, string jsonName, object o) { StringBuilder jsStr = new StringBuilder(); jsStr.Append("{"); jsStr.AppendFormat("\"State\":{0},\"{1}\":\"{2}\"", state, jsonName, ser.Serialize(o)); jsStr.Append("}"); return jsStr.ToString(); } public static string GetJson(int state, string msg, string jsonName, object o) { StringBuilder jsStr = new StringBuilder(); jsStr.Append("{"); jsStr.AppendFormat("\"State\":{0},\"Msg\":\"{1}\",\"{2}\":{3}", state, msg, jsonName, ser.Serialize(o)); jsStr.Append("}"); return jsStr.ToString(); } }
上面一段是我写了个公共方法类,主要还是够着JSON格式的字符串,写了几个能用上的重载方法!
public partial class JsonTest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //var row List<Test> ls = new List<Test>(); ls.Add(new Test() { SonOne = "AA", SonTwo = "AAA", ID = 1 }); ls.Add(new Test() { SonOne = "BB", SonTwo = "BBB", ID = 2 }); ls.Add(new Test() { SonOne = "CC", SonTwo = "CCC", ID = 3 }); ls.Add(new Test() { SonOne = "DD", SonTwo = "DDD", ID = 4 }); string options = HttpContext.Current.Request["Option"]; if (options == "Search") { var row = ls.Select(r => new { SO1 = r.SonOne, SO2 = r.SonTwo }).ToList(); Response.Write(Common.DataToJson.GetJson(1,"Success","Row",row)); Response.End(); } } } public class Test { public string SonOne { get; set; } public string SonTwo { get; set; } public int ID { get; set; } }
上面一段构造了一个JsonTest.aspx也面然后构造个Test数据类,这里为了方便直接写在下面。其中row就是为了构造个匿名集合好测试用。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JsonTest.aspx.cs" Inherits="MyTest.JsonTest" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="Scripts/jquery-1.10.2.js"></script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" id="btn" value="按钮" /> </div> </form> </body> <script type="text/javascript"> $(function () { $('#btn').click(function () { var da = "ID=10010"; $.ajax({ type: 'GET', data: { Option: "Search" }, url: '/JsonTest.aspx', dataType: 'JSON', success: function (result) { alert(result.State); }, error: function () { } }); }); }); </script> </html>
上面就是简单的前端测试代码!
当然也有Newtonsoft.Json.dll。这个也很好用,教程网上随便一搜就可以!