Finding JSON for C#

I’m reacquainting myself with C# and learning the new ASP.NET Core. Finding a good library for JSON serialization/deserialization was harder than I expected, so I thought I’d try to leave some bread crumbs for future explorers.  (If you are working in C++, take a look at post JSON Serialization for C++.)

In short, install Newtonsoft.Json,  an Open Source, easy license package.  You can read about it here.  The package can be installed with NuGet, or you can download source and binaries from here.

C# Sample

A tiny sample project can be downloaded from my  GitHub, FindingJsonDotNet . It demonstrates the following brief example of creating a JSON string:

public class Program
{
    public static void Main(string[] args)
    {
        StringWriter sw = new StringWriter(new StringBuilder());
        JsonWriter jw = new JsonTextWriter(sw);

        jw.WriteStartObject();
        jw.WritePropertyName("School");
        jw.WriteValue("University of Alabama");
        jw.WritePropertyName("Sport");
        jw.WriteValue("Football");
        jw.WritePropertyName("Ranking");
        jw.WriteValue(1);
        jw.WriteEndObject();

        Console.WriteLine($"Roll Tide! {sw.ToString()}");
    }
}

Installing Json.Net with VisualStudio and NuGet

An easy way to install the N is with VisualStudio‘s NuGet package manager to import package Newtonsoft.Json.

  1. Right click on References in the Solutions pane
    solutionexplorer
  2. Select “Manage NuGet Packages…”
  3. In the NuGet window, select Browse

    nuget
  4. Install the Newtonsoft.Json package.
Advertisements

3 thoughts on “Finding JSON for C#

  1. gregsdennis says:

    You should really check out [Manatee.Json](https://github.com/gregsdennis/Manatee.Json). It’s a lot simpler to use. The code you posted would be:

    public class Program
    {
    public static void Main(string[] args)
    {
    var json = new JsonObject
    {
    [“School”] = “University of Alabama”,
    [“Sport”] = “Football”,
    [“Ranking”] = 1
    };

    Console.WriteLine($”Roll Tide! {json}”);
    }
    }

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s