Convert structure to JSON

I have a structure, I want to convert it to JSON and save it as a local file.

I could not find a source explaining how to convert a C # structure to JSON.

I use a console application for this, not webservice / web, etc.

+4
source share
2 answers

JavaScriptSerializer Class

var serializer = new JavaScriptSerializer(); YourStruct myStruct = new YourStruct(x,y,z); var json = serializer.Serialize(myStruct); 

JSON.NET

Another alternative to JSON.net, it is not dependent on System.Web. * assemblylies:

 YourStruct myStruct = new YourStruct(x,y,z); var json = JsonConvert.SerializeObject(myStruct); 
+8
source

I would recommend using JSon.net . Then you can do something like:

 string json = JsonConvert.SerializeObject(myObj); // myObj is the struct you want to serialize File.WriteAllText("Foo.json", json); //Write the text to Foo.json 
0
source

All Articles