Convert Struct to JSON

19,933

Solution 1

JavaScriptSerializer Class

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

JSON.NET

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
Share:
19,933

Related videos on Youtube

m0fo
Author by

m0fo

Updated on September 17, 2022

Comments

  • m0fo
    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
    Sean U over 11 years
    JavaScriptSerializer is in in an ASP.NET assembly.
  • Marcelo De Zen
    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
    Mike Christensen over 11 years
    Nothing would stop you from referencing System.Web.Extensions.dll in a console app..
  • Mike Christensen
    Mike Christensen over 11 years
    You also can't name a variable struct unless you use @struct :)
  • Sean U
    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
    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
    DonCarleone over 3 years
    Thanks @MarceloDeZen !