newtonsoft json code example

Example 1: json nuget package manager

Install-Package Newtonsoft.Json -Version 12.0.3

Example 2: newtonsoft json c# code project example

using Newtonsoft.Json;
using System.Collections.Generic;

namespace Support.CSharp
{
    public static class JsonHelper
    {
        public static string FromClass<T>(T data, bool isEmptyToNull = false,
                                          JsonSerializerSettings jsonSettings = null)
        {
            string response = string.Empty;

            if (!EqualityComparer<T>.Default.Equals(data, default(T)))
                response = JsonConvert.SerializeObject(data, jsonSettings);

            return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
        }

        public static T ToClass<T>(string data, JsonSerializerSettings jsonSettings = null)
        {
            var response = default(T);

            if (!string.IsNullOrEmpty(data))
                response = jsonSettings == null
                    ? JsonConvert.DeserializeObject<T>(data)
                    : JsonConvert.DeserializeObject<T>(data, jsonSettings);

            return response;
        }
    }
}

Example 3: asp net core use newtonsoft json

services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages().AddNewtonsoftJson();

Example 4: 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