user1429595 user1429595 - 1 month ago 13
JSON Question

How to write a Json file in C#?

Hi I need to write the following data into a text file using Json format in C#? BRACKETS are important to be valid JSON FORMAT

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

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


and here is my model class

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

}

Answer

I would recommend Json.Net

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

Documentation: Serialize JSON to a file


Why? Here's a feature comparision between common serialisers as well as benchmark tests (see graph below)* .

enter image description here

This test, states that "Json.Net allocates 8 times less memory than JavaScriptSerializer"**.

* Benchmarks appear to be Json.Net 5, the current version (on writing is 8). What version of standard .Net serialisers used is not mentioned

** These tests are obviously from the developers who maintian the library. I have not verified their claims. If in doubt test them yourself.

Comments