2011-12-05 74 views
24

我爲我的網站創建自動填充功能。 到目前爲止,javascript部分已經結束。另外,我可以獲得匹配用戶的MembershipUser對象。ASP.NET返回JSON與ASHX

我需要在以下格式返回JSON:

{ 
query:'Li', 
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'], 
data:['LR','LY','LI','LT'] 
} 

,這是ASHX代碼:

public void ProcessRequest (HttpContext context) { 
    System.Web.Script.Serialization.JavaScriptSerializer JsonSerializer; 
    string query = context.Request.QueryString["query"]; 
    System.Web.Security.MembershipUserCollection Users = System.Web.Security.Membership.GetAllUsers(); 
    context.Response.ContentType = "application/json"; 
    foreach (System.Web.Security.MembershipUser User in Users) 
    { 
     if (User.UserName.StartsWith(query.ToLower())) 
     { 
      context.Response.Write(query + Environment.NewLine); 
      context.Response.Write(User.Email); 
     } 
    } 
} 

我怎樣才能返回JSON所需格式? 謝謝。

+2

不由的方式有效的JSON。請參閱:http://json.org/ – ChaosPandion

+0

ChaosPandion,該插件需要此​​輸出...:/ – user1027620

回答

29
context.Response.Write(
    jsonSerializer.Serialize(
     new 
     { 
      query = "Li", 
      suggestions = new[] { "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania" }, 
      data = new[] { "LR", "LY", "LI", "LT" } 
     } 
    ) 
); 
5

創建具有基於你想要的回報合同一類,然後使用JSONSerializer在這個類的一個實例來創建你的回報內容

[DataContract] 
public class YourReturnObject { 
    [DataMember(Name="query")] 
    public String Query { get;set;} 

    [DataMember(Name="suggestions")] 
    public String[] Suggestions { get;set;} 

    [DataMember(Name="data")] 
    public String[] OtherData{ get;set;} 
} 
+2

嗨,謝謝你的回答。您能否解釋一下,這是如何在for循環中實現的? – user1027620

+2

如果您可以提供更多詳細信息,我會投票贊成@Tim – MacGyver

5

您的JSON是一個有點尷尬,因爲你有保持這兩個數組的索引。我可以建議更像這樣的東西嗎?

{ 
query: 'Li', 
data: [{id:'LR', text:'Liberia'}, {id:'LY', text:'Libyan Arab Jamahiriya'}, ...] 
} 
16

這有助於我:

using System; 
using System.Data; 
using System.Web; 
using System.Linq; 
using System.Collections; 
using Newtonsoft.Json; 

public class Handler : IHttpHandler { 

public void ProcessRequest (HttpContext context) { 
    context.Response.ContentType = "application/json"; 
    string quer = context.Request["query"]; 

    DataTable _t = AMC.Core.Logic.Root.Storage.ExecuteQuery("SELECT [tag_name] FROM [tags] Where [tag_name] like '%' + @ke + '%'", new System.Data.SqlClient.SqlParameter("ke", quer)); 

    DataRow[] list = new DataRow[_t.Rows.Count]; 
    _t.Rows.CopyTo(list, 0); 

    var wapper = new { 
     query = quer 
     , suggestions = (from row in list select row["tag_name"].ToString()).ToArray() 
     //, data = new[] { "LR", "LY", "LI", "LT" } 
    }; 
    context.Response.Write(JsonConvert.SerializeObject(wapper));    
} 

Newtonsoft.Json將在這裏找到:http://json.codeplex.com/releases/

+2

只需在IE8中添加(僅限於?),它將在調用時失敗。彈出一個對話框詢問您是否要打開或保存文件「handler.ashx」。要解決此問題,請將代碼行更改爲返回文本: context.Response.ContentType =「text/html」; –