How to write a JSON file in C#?

445,221

Solution 1

Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:

  • .Net Core now has the spookily similar System.Text.Json serialiser (see below)
  • The days of the JavaScriptSerializer have thankfully passed and this class isn't even in .Net Core. This invalidates a lot of the comparisons ran by Newtonsoft.
  • It's also recently come to my attention, via some vulnerability scanning software we use in work that Json.Net hasn't had an update in some time. Updates in 2020 have dried up and the latest version, 12.0.3, is over a year old (2021).
  • The speed tests (previously quoted below but now removed as they are so out of date that they seem irrelevant) are comparing an older version of Json.Net (version 6.0 and like I said the latest is 12.0.3) with an outdated .Net Framework serialiser.
  • One advantage the System.Text.Json serializer has over Newtonsoft is it's support for async/await

Are Json.Net's days numbered? It's still used a LOT and it's still used by MS libraries. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.


.Net Core 3.0+ and .Net 5

A new kid on the block since writing this is System.Text.Json which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. I'd advise you to test this yourself .

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


Newtonsoft Json.Net (.Net framework and .Net Core)

Another option is Json.Net, see example 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);

Or the slightly more efficient version of the above code (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);
}

Documentation: Serialize JSON to a file

Solution 2

The example in Liam's answer saves the file as string in a single line. I prefer to add formatting. Someone in the future may want to change some value manually in the file. If you add formatting it's easier to do so.

The following adds basic JSON indentation:

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

Solution 3

There is built in functionality for this using the JavaScriptSerializer Class:

var json = JavaScriptSerializer.Serialize(data);

Solution 4

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

Related videos on Youtube

user1429595
Author by

user1429595

Updated on December 09, 2021

Comments

  • user1429595
    user1429595 over 2 years

    I need to write the following data into a text file using JSON format in C#. The brackets are important for it to be valid JSON format.

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

    Here is my model class:

    public class data
    {
        public int Id { get; set; }
        public int SSN { get; set; }
        public string Message { get; set;}
    }
    
  • Yinda Yin
    Yinda Yin almost 11 years
    How does JSON.NET differ from the built-in support provided by the JavaScriptSerializer and DataContractJsonSerializer classes?
  • Tim S.
    Tim S. almost 11 years
    @RobertHarvey Liam's Json.Net link has a nice table showing what the differences are. Coming from the people that make it, of course you should take it with a grain of salt, but it is indeed better than the built-in things.
  • user1429595
    user1429595 almost 11 years
    Yes I need to Append to the file over and over again, but they need to be all in the same array
  • Drew Noakes
    Drew Noakes over 10 years
    I'm interested to know if this can be done without buffering the string in memory. Do you know?
  • gcoleman0828
    gcoleman0828 almost 10 years
    @Drew Noakes If you want to do write to a file without putting it in memory first, try this write from JSON.NET james.newtonking.com/archive/2009/02/14/…
  • JohnnyAce
    JohnnyAce almost 7 years
    If you want to include the indentation you can use serializer.Formatting = Formatting.Indented;.
  • Wang Jijun
    Wang Jijun almost 7 years
    use the second method : serializer.Serialize(file, _data);I have met a problem when I try to Deserizailzer the the json string from the file created before. In the json file, there were not unneeded characters like '\' and '"' which will cause the failure of Deserialized .
  • Tarostar
    Tarostar over 2 years
    According to MS documentation you reference you are missing the await createStream.DisposeAsync(); in the second System.Text.Json example.
  • Liam
    Liam over 2 years
    Thanks @Tarostar I had forgotten to dispose of the stream correctly. But I don't need to call DisposeAsync directly as I am using a using. But I had neglected the await for the async disposing.