Reputation: 2755
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;}
}
Upvotes: 221
Views: 622261
Reputation: 8472
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.
Upvotes: 2
Reputation: 29674
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:
System.Text.Json
serializer (see below)JavaScriptSerializer
have thankfully passed and this class isn't even in .NET Core. This invalidates a lot of the comparisons ran by Newtonsoft.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.
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);
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
Upvotes: 437
Reputation: 71
var responseData = //Fetch Data
string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);
Upvotes: 6
Reputation: 50493
There is built in functionality for this using the JavaScriptSerializer Class:
var json = JavaScriptSerializer.Serialize(data);
Upvotes: 8
Reputation: 1057
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);
Upvotes: 81