Convert Struct to JSON
19,933
Solution 1
var serializer = new JavaScriptSerializer();
YourStruct myStruct = new YourStruct(x,y,z);
var json = serializer.Serialize(myStruct);
The other alternative JSON.net, it do not depends on System.Web.* assemblies:
YourStruct myStruct = new YourStruct(x,y,z);
var json = JsonConvert.SerializeObject(myStruct);
Solution 2
I would recommend using JSon.net. You can then 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
Related videos on Youtube
Author by
m0fo
Updated on September 17, 2022Comments
-
m0fo over 1 year
I have a struct, I want to convert it to JSON and save it as local file.
I couldn't find any source that explain how to convert a C# struct into a JSON.
I am using a console application for that, not a webservice/web, etc.
-
Sean U over 11 yearsJavaScriptSerializer is in in an ASP.NET assembly.
-
Marcelo De Zen over 11 years@SeanU, that's true. He didn't asked for a specific approach. But I'll put a example with JSON.net
-
Mike Christensen over 11 yearsNothing would stop you from referencing System.Web.Extensions.dll in a console app..
-
Mike Christensen over 11 yearsYou also can't name a variable
struct
unless you use@struct
:) -
Sean U over 11 years@MikeChristensen As long as it's installed. But ASP.NET components aren't included in the client profile, so I figured it was worth mentioning.
-
Marcelo De Zen over 3 years@DonCarleone yes, nothing changed. On .NETCore there's the new Json library from Microsoft, but the workings are the same.
-
DonCarleone over 3 yearsThanks @MarceloDeZen !