ASP.NET使用ASHX返回JSON

时间:2011-12-05 21:53:59

标签: c# jquery asp.net ajax json

我正在为我的网站创建自动填充功能。 到目前为止,javascript部分已经结束了。此外,我可以获得匹配的用户的MembershipUser对象。

我需要以下列格式返回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? 感谢。

4 个答案:

答案 0 :(得分:35)

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

答案 1 :(得分:18)

这有助于我:

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 :(得分: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;} 
}

答案 3 :(得分:5)

你的json有点尴尬,因为你必须维护这两个数组的索引。我可以建议更像这样的东西吗?

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