newtonsoft json serialize c# code example

Example 1: 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 2: object to json c#

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);

Example 3: c# newtonsoft serialize dictionary to json

Dictionary<string, int> points = new Dictionary<string, int>
{
    { "James", 9001 },
    { "Jo", 3474 },
    { "Jess", 11926 }
};

string json = JsonConvert.SerializeObject(points, Formatting.Indented);

Console.WriteLine(json);
// {
//   "James": 9001,
//   "Jo": 3474,
//   "Jess": 11926
// }

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