Coder Perfect

In C#, how do you make a JSON file?

Problem

In C#, I need to write the following information to a text file in JSON format. The brackets are required for the JSON format to be valid.

[
  {
    "Id": 1,
    "SSN": 123,
    "Message": "whatever"

  },
  {
   "Id": 2,
    "SSN": 125,
    "Message": "whatever"
  }
]

My model class is as follows:

public class data
{
    public int Id { get; set; }
    public int SSN { get; set; }
    public string Message { get; set;}
}

Asked by user1429595

Solution #1

Update for the year 2020: I’ve been writing this response for 7 years. It appears to be attracting a lot of interest. Newtonsoft Json.Net was THE solution to this problem in 2013. It is still a good solution to this problem, but it is no longer the sole one. To update this response, here are some current caveats:

Is Json.time Net’s coming to an end? It’s still widely used, and MS libraries still utilize it. So, most likely, no. However, this appears to be the beginning of the end for this library, which may have reached the end of its useful life.

System is a new kid on the street since I wrote this. Text.Json is a new addition to the. 3.0 is the latest version of Net Core. Microsoft argues that this is now better than Newtonsoft in several ways. It also outperforms Newtonsoft in terms of speed. I recommend that you put this to the test.

Examples:

using System.Text.Json;
using System.Text.Json.Serialization;

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonSerializer.Serialize(_data);
File.WriteAllText(@"D:\path.json", json);

or

using System.Text.Json;
using System.Text.Json.Serialization;

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

await using FileStream createStream = File.Create(@"D:\path.json");
await JsonSerializer.SerializeAsync(createStream, _data);

Documentation

Json.Net is another option, as shown below:

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonConvert.SerializeObject(_data.ToArray());

//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);

Alternatively, here’s a little faster version of the above code that doesn’t use a string as a buffer:

//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
     JsonSerializer serializer = new JsonSerializer();
     //serialize object directly into file stream
     serializer.Serialize(file, _data);
}

Serialize JSON to a file, as stated in the documentation.

Answered by Liam

Solution #2

The example in Liam’s response saves the file as a single line string. Formatting is something I prefer to do. Someone may want to update a value in the file manually in the future. It’s easier to do so if you add formatting.

Basic JSON indentation is added as follows:

 string json = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);

Answered by MichaƂ S.

Solution #3

The JavaScriptSerializer Class has built-in capabilities for this:

var json = JavaScriptSerializer.Serialize(data);

Answered by Gabe

Solution #4

var responseData = //Fetch Data
string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);

Answered by Kulwant Singh

Post is based on https://stackoverflow.com/questions/16921652/how-to-write-a-json-file-in-c