在C#中,您可以使用JsonConvert类将对象转换为JSON字符串,并将其作为响应发送回客户端。以下是一个示例代码片段,演示如何发送JSON响应:
using System; using System.Net; using System.Text; using Newtonsoft.Json; class Program { static void Main() { var data = https://www.yisu.com/ask/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"。