using Newtonsoft.Json; using System.IO; using System.Threading.Tasks; public async Task WriteJsonToFileAsync(string json, string filePath) { using(var streamWriter = new StreamWriter(filePath)) { using(var jsonWriter = new JsonTextWriter(streamWriter)) { await jsonWriter.WriteRawAsync(json); await jsonWriter.FlushAsync(); } } }
using Newtonsoft.Json; using System.IO; using System.Net; using System.Threading.Tasks; public async Task WriteJsonToResponseAsync(object data, HttpListenerResponse response) { response.ContentType = "application/json"; using(var streamWriter = new StreamWriter(response.OutputStream)) { using(var jsonWriter = new JsonTextWriter(streamWriter)) { var serializer = new JsonSerializer(); serializer.Serialize(jsonWriter, data); await jsonWriter.FlushAsync(); } } }In this example, the WriteJsonToResponseAsync method writes JSON data to an HttpListenerResponse stream. The JsonTextWriter is used to serialize the provided data using a JsonSerializer. The FlushAsync method is called to ensure that all data is written to the response stream before the method returns. Package library: Newtonsoft.Json (also known as Json.NET)