【问题标题】:ASP.NET Returning JSON with ASHXASP.NET 使用 ASHX 返回 JSON
【发布时间】:2012-01-13 14:41:54
【问题描述】:

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

【问题讨论】:

  • 顺便说一句,这不是有效的 JSON。见:json.org
  • ChaosPandion,插件需要这个输出...:/

标签: c# jquery asp.net ajax json


【解决方案1】:
context.Response.Write(
    jsonSerializer.Serialize(
        new
        {
            query = "Li",
            suggestions = new[] { "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania" },
            data = new[] { "LR", "LY", "LI", "LT" }
        }
    )
);

【讨论】:

    【解决方案2】:

    这对我有帮助:

    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/

    【讨论】:

    • 只是添加,在 IE8 中(仅?)它在调用时会失败。将弹出一个对话框,询问您是否要打开或保存文件“handler.ashx”。要解决此问题,请将代码行更改为返回文本: context.Response.ContentType = "text/html";
    【解决方案3】:

    根据您想要的回报创建一个具有合同的类,然后在该类的实例上使用 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;} 
    }
    

    【讨论】:

    • 您好,感谢您的回答。能否请您解释一下这是如何在 for 循环中实现的?
    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-02-11
      • 1970-01-01
      • 2019-05-01
      • 2011-03-01
      • 1970-01-01
      • 2011-02-26
      • 2017-07-20
      • 2013-03-21
      • 2010-09-27
      相关资源
      最近更新 更多