在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"。