简体   繁体   English

ASP.NET使用ASHX返回JSON

[英]ASP.NET Returning JSON with ASHX

I am creating autocomplete functionality for my website. 我正在为我的网站创建自动完成功能。 So far, the javascript part is over. 到目前为止,javascript部分已经结束了。 Also, I can get the MembershipUser object of the user that matches. 此外,我可以获得匹配的用户的MembershipUser对象。

I need to return JSON in the following format: 我需要以下列格式返回JSON:

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

and this is the code in ashx: 这是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);
        }
    }
}

How can I return the json in the desired format? 如何以所需格式返回json? Thanks. 谢谢。

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

This helps me: 这有助于我:

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 will be found here: http://json.codeplex.com/releases/ Newtonsoft.Json将在这里找到: http//json.codeplex.com/releases/

Create a class that has a contract based on the return you want, and then use the JSONSerializer on an instance of that class to create your return content 根据所需的返回创建一个具有契约的类,然后在该类的实例上使用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;} 
}

your json is a little awkward since you have to maintain an index into both of those array. 你的json有点尴尬,因为你必须维护这两个数组的索引。 might I suggest something more like this? 我可以建议更像这样的东西吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM