#100DaysOfCode - Day 96: C# External Library Testing with .NET Interactive Prompt (Newtonsoft.Json)

#100DaysOfCode - Day 96: C# External Library Testing with .NET Interactive Prompt (Newtonsoft.Json)

2 mins

Today I got to mess around with JSON ([See example for JSON]](https://json.org/example.html)), and in particular, the Newtonsoft.JSON package in C#/DOTNET. I’ve always used this package, but disliked working with it when compared to working with the key-value format in something more dynamic, such as Python.

To work through my compilation based bottleneck, I decided to finally try out the C# Interactive prompt, which allows you to run one-line (or multi-line) commands similar to how you would run things in a terminal. The syntax is compiled and ran in real time, which is really cool for a pre-compiled language like C#. So, no need to recompile my code and get to the point of execution every time.

Unfortunately, there was a bug with C# interactive that wouldn’t let me import packages in the nuget way, such as syntax using the documented syntax (e.g. #r "nuget:System.Text.Json,4.7.2"), but I was able to get Newtonsoft installed via the compiled package’s .dll I had downloaded, so this worked:

#r "C:\Users\Marc Ochsner\source\repos\TestProject\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll"

And, well, it turns out this interactive mode was REALLY helpful. Not only did it let me quickly run my code, but it actually let me output these JObjects and display the type right alongside them.

So I made an Object:

var jso1 = Newtonsoft.Json.Linq.JObject.Parse("{'a':['1',{'2':'2a'}]}");

Output it the key/value pairs:

> Console.WriteLine(jso1);
{
  "a": [
    "1",
    {
      "2": "2a"
    }
  ]
}

And didn’t want to type Console.Writeline every time, so I tried it without just to see what happened (would it be similar to Powershell??!)

> jso1
JObject(1) { JProperty(1) { JArray(2) { [1], JObject(1) { JProperty(1) { [2a] } } } } }

…AND IT’S ALMOST LIKE I’M USING C# IN POWERSHELL MODE! :D Wonderful, so I have the types I was using for my development just written right there for me.

Here’s a quick summary of what each maps to in JSON:

// JObject
{ 
  // Jproperty
  "a":
  // JArray
  [
    // [Value]
    "1",
    // JObject
    {
      // JProperty
      "2": 
      // [Value]
      "2a"
    }
  ]
}

Hopefully this helped someone like it did me! Happy coding ya’ll.

-Marc

Written on August 13, 2021