write string array in json file in csharp

To write a string array into a JSON file in C#, we first need to serialize the array into a JSON format using the JsonSerializer class provided by the System.Text.Json namespace. Then, we can simply write the serialized string into a file using any file handling technique, such as StreamWriter or the File.WriteAllText() method.

Here's an example code snippet demonstrating how to write a string array into a JSON file using the JsonSerializer and StreamWriter classes:

main.cs
using System;
using System.IO;
using System.Text.Json;

class Program
{
    static void Main(string[] args)
    {
        // The string array to be written as JSON
        string[] fruits = new string[] { "Apple", "Banana", "Orange", "Grapes" };

        // Serialize the string array into a JSON string
        string jsonString = JsonSerializer.Serialize(fruits);

        // Write the JSON string into a file using StreamWriter
        using (StreamWriter sw = new StreamWriter("fruits.json"))
        {
            sw.Write(jsonString);
        }
    }
}
559 chars
22 lines

In the above example, the JsonSerializer.Serialize() method is used to serialize the fruits array into a JSON string, which is then written into a file named fruits.json using the StreamWriter class.

Alternatively, we can use the File.WriteAllText() method to write the serialized JSON string into a file in a more concise way:

main.cs
// Write the JSON string into a file using File.WriteAllText
File.WriteAllText("fruits.json", jsonString);
107 chars
3 lines

gistlibby LogSnag