How to store C # structure to JSON string?

Question:

How to store C # structure to JSON string?

Answer:

Also try not to bypass the good Newtonsoft.JSON library

A trivial example of use. There is a UserInfo structure:

struct UserInfo
{
    public string Name;
    public byte Age;
}

Serialization might look like this:

var data = new UserInfo {Name = "Ivan", Age = 42};

string serialized = JsonConvert.SerializeObject(data, Formatting.Indented);

At the output we have:

{
  "Name": "Ivan",
  "Age": 42
}

You can override field names in json:

struct UserInfo
{
    [JsonProperty("username")]
    public string Name;

    public byte Age;
}

We get:

{
  "username": "Ivan",
  "Age": 42
}

Etc. The library is very powerful, read the documentation.

Scroll to Top