newtonsoft json serialize code example

Example 1: c# serialize json

using System.Text.Json;

//Serialize
var jsonString = JsonSerializer.Serialize(yourObject);

// Deserialize
var obj = JsonSerializer.Deserialize<YourObject>(stringValue);

Example 2: c# newtonsoft json serialize

Account account = new Account
{
    Email = "[email protected]",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    Roles = new List<string>
    {
        "User",
        "Admin"
    }
};

string json = JsonConvert.SerializeObject(account, Formatting.Indented);
// {
//   "Email": "[email protected]",
//   "Active": true,
//   "CreatedDate": "2013-01-20T00:00:00Z",
//   "Roles": [
//     "User",
//     "Admin"
//   ]
// }

Console.WriteLine(json);

Example 3: object to json c#

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);

Example 4: c# newtonsoft json serialize

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}

Example 5: fsharp newtonsoft json deserialize

type Foo =
  { meta : Meta }
and Meta =
  { count : int }

let testjson = """{"meta": {"count": 15}}"""

open FSharp.Json
let data = Json.deserialize<Foo> testjson