ASP.使用ASHX返回JSON

本文关键字:JSON 返回 ASHX 使用 ASP | 更新日期: 2023-09-27 18:16:56

我正在为我的网站创建自动完成功能。到目前为止,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 ?谢谢。

ASP.使用ASHX返回JSON

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

这对我有帮助:

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/

创建一个基于您想要的返回值的契约的类,然后在该类的实例上使用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;} 
}

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

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