224

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;}
}
0

5 Answers 5

442

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 serializer (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.
  • 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

Sign up to request clarification or add additional context in comments.

7 Comments

How does JSON.NET differ from the built-in support provided by the JavaScriptSerializer and DataContractJsonSerializer classes?
@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.
Yes I need to Append to the file over and over again, but they need to be all in the same array
@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/…
If you want to include the indentation you can use serializer.Formatting = Formatting.Indented;.
|
82

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);

1 Comment

I got errorhen used your approach: The process cannot access the file 'my full path file' because it is being used by another process. It saves OK If I use Liam's example with JsonSerializer serializer = new JsonSerializer(); //serialize object directly into file stream serializer.Serialize(file, _data);
9

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

var json = JavaScriptSerializer.Serialize(data);

Comments

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

Comments

5

If you have data structures that directly match whatever you're putting into JSON, then using JsonSerialize is the way to go. But that's not the only thing .Net supports. I wanted to include this other way so those searching know that .Net includes this other interface.

Sometimes you don't want to just serialize C# directly, possibly because you're dealing with legacy code, multiple codebases, weird JSON interfaces, or who knows what. It's possible to create JSON "by hand" using .Net. The following writes a list of data objects to a file, but there are other functions if (eg) you want to return the Json from an HTTP request. And, of course, there are Read equivalents of all these functions.

using System.Text.Json;

public void WriteDataList(string filename, IEnumerable<data> dataList)
{
    var filestream = File.OpenWrite(filename);
    var writer = new Utf8JsonWriter(filestream);
    writer.WriteStartArray();
    foreach (var dataItem in dataList) {
        writer.WriteStartObject();
        writer.WriteNumber("Id", dataItem.Id);
        writer.WriteNumber("SSN", dataItem.SSN);
        writer.WriteString("Message", dataItem.Message);
        writer.WriteEndObject();
    }
    writer.WriteEndArray();
    writer.Flush();
    filestream.Close();
}

There are also WriteValue functions if you need to, eg, fill out an array. Intellisense, typeahead, and Google should get you the rest of the way there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.