以json格式显示响应的最佳方法? [英] Best method to show response in json format?

查看:170
本文介绍了以json格式显示响应的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用web应用程序。用户可以调用我的aspx页面。我以querystring的形式从用户那里获取输入。我想以json的形式给客户端回复。这是在json中显示响应的最佳方法格式



I am using web application.User can call my aspx page.I am taking input from user in the form of querystring.I want to give response to client in the form of json.Which is best method to show response in json format

try
        {
            string json = "message{\"description\":\""+description+"\"Id\":\""+id+"}";
            Response.Clear();
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write(json);
           // Response.End();

            HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
            HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
            HttpContext.Current.ApplicationInstance.CompleteRequest(); 

            //HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        catch(Exception ex)
        {
            Response.Write(ex.ToString());
        }

或创建一个类并进行serilize.Which一个是最好的方法?



我尝试过:



or create a class and do serilize.Which one is best method?

What I have tried:

try
        {
            string json = "message{\"description\":\""+description+"\"Id\":\""+id+"}";
            Response.Clear();
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write(json);
           // Response.End();

            HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
            HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
            HttpContext.Current.ApplicationInstance.CompleteRequest(); 

            //HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        catch(Exception ex)
        {
            Response.Write(ex.ToString());
        }

推荐答案

您好,

您可以使用以下方法从Object转换JSON字符串。

Hi,
You can use following method to convert JSON string from Object.
public class Message
{
    public string Description { get; set; }
    public int Id { get; set; }  
}
Message myReturnData = new Message() { Description = "This is test description", Id = 1 };
string json = JsonConvert.SerializeObject(myReturnData);



你必须参考newtonsoft JSON图书馆简介 [ ^ ]



问候,

Imdadhusen


You must have reference of newtonsoft JSON Library Introduction[^]

Regards,
Imdadhusen


您好b $ b

我建议您将方法更改为[WebMethod],返回类型为Dynamic / Object,并将结果序列化为JSON。



使用AJAX将您的请求发送到该网络方法。
Hi
I would recommend you change your method to [WebMethod] with return type of Dynamic/Object and serialize your results to JSON.

Send your requests to that web method using AJAX.


这篇关于以json格式显示响应的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆