write array in json file in csharp

To write an array in a JSON file using C#, we need to follow these steps:

  1. Create an array of objects
  2. Serialize the array to JSON format
  3. Write the serialized JSON string to a file

Here is an example code snippet that demonstrates how to write an array of objects to a JSON file in C#:

main.cs
using System;
using System.IO;
using System.Text.Json; // Required library for serialization

class Program {
    static void Main(string[] args) {
        // Step 1: Create an array of objects
        Person[] people = {
            new Person("John", 30),
            new Person("Jane", 25),
            new Person("Mike", 40)
        };

        // Step 2: Serialize the array to JSON format
        string json = JsonSerializer.Serialize(people);

        // Step 3: Write the serialized JSON string to a file
        File.WriteAllText("people.json", json);
    }
}

class Person {
    public string Name { get; set; }
    public int Age { get; set; }

    public Person(string name, int age) {
        Name = name;
        Age = age;
    }
}
747 chars
31 lines

In this example, we create an array of Person objects, serialize it to JSON format using JsonSerializer.Serialize(), and then write the serialized JSON string to a file using File.WriteAllText(). We use the System.Text.Json library for serialization which is built-in to .NET Core 3.0 and later versions. If you are using .NET Framework or an older version of .NET Core, you can use the Newtonsoft.Json library instead.

gistlibby LogSnag