In many cases, we may not be able to access Newtonsoft.Json package. Like sometime there might be different packages using different versions of it, which may cause version conflict via build. That usually happens in some projects really large.

So how can we play with JSON as while without it? In pure C#?

First, copy the following class to your project:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

public static class MyJsonConverter
{
    /// <summary>
    /// Deserialize an from json string
    /// </summary>
    public static T Deserialize<T>(string body)
    {
        using (var stream = new MemoryStream())
        using (var writer = new StreamWriter(stream))
        {
            writer.Write(body);
            writer.Flush();
            stream.Position = 0;
            return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(stream);
        }
    }

    /// <summary>
    /// Serialize an object to json
    /// </summary>
    public static string Serialize<T>(T item)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            new DataContractJsonSerializer(typeof(T)).WriteObject(ms, item);
            return Encoding.Default.GetString(ms.ToArray());
        }
    }
}

Now, it's done. You can try it just like using Newtonsoft.Json:

var json = MyJsonConverter.Serialize(YourObject);
var deserialize = MyJsonConverter.Deserialize<YourType>(json);

Let's do a test. Create a simple class:

public class Book
{
    public string Name { get; set; }
    public List<Book> Related { get; set; }
}

And try to serialize it.

class Program
{
    static void Main(string[] args)
    {
        var book = new Book
        {
            Name = "My book.",
            Related = new List<Book>()
            {
                new Book
                {
                    Name = "My book 2.",
                },
                new Book
                {
                    Name = "My book 3.",
                },
            }
        };
        var json = MyJsonConverter.Serialize(book);
        Console.WriteLine(json);

        var deserialize = MyJsonConverter.Deserialize<Book>(json);
        Console.WriteLine(deserialize.Name);
    }
}

The output is:

{"Name":"My book.","Related":[{"Name":"My book 2.","Related":null},{"Name":"My book 3.","Related":null}]}
My book.