C# Response如何发送JSON响应

   2024-10-08 5960
核心提示:在C#中,您可以使用JsonConvert类将对象转换为JSON字符串,并将其作为响应发送回客户端。以下是一个示例代码片段,演示如何发送J

在C#中,您可以使用JsonConvert类将对象转换为JSON字符串,并将其作为响应发送回客户端。以下是一个示例代码片段,演示如何发送JSON响应:

using System;using System.Net;using System.Text;using Newtonsoft.Json;class Program{    static void Main()    {        var data = new { Name = "John", Age = 30 };        var json = JsonConvert.SerializeObject(data);        HttpListener listener = new HttpListener();        listener.Prefixes.Add("http://localhost:8080/");        listener.Start();        Console.WriteLine("Listening for requests...");        while (true)        {            HttpListenerContext context = listener.GetContext();            HttpListenerRequest request = context.Request;            HttpListenerResponse response = context.Response;            byte[] buffer = Encoding.UTF8.GetBytes(json);            response.ContentType = "application/json";            response.ContentLength64 = buffer.Length;            response.OutputStream.Write(buffer, 0, buffer.Length);            response.Close();        }    }}

在上面的示例中,我们创建了一个包含名称和年龄属性的匿名对象,并将其转换为JSON字符串。然后我们创建了一个HttpListener实例来监听HTTP请求。当有请求到达时,我们将JSON字符串作为响应发送回客户端,并设置适当的Content-Type为"application/json"。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号