How to best handle JSON deserialization in c# Script

Hi Everyone,

I’m writing some custom step templates which will call out to external APIs as part of the deployment and make the appropriate actions based on the response.

As the responses all come back as JSON I’d love to be able to deserialize this into a useful .Net object.

Ideally I don’t want to introduce any dependencies on external libraries such as Newtonsoft Json.Net and have so far been doing complex string logic to manually interpenetrate the results which works for small tasks but now I need to deserialize an array and string manipulation would make the whole script too hard to read and generally seems like a complicated way to achieve what should be simple.

I’ve had a try to use some more native libraries such as System.Web.Script.Serialization.JavaScriptSerializer however when I try to reference #r “System.Web.Script.Serialization” I get a [FileNotFoundException] Assembly not found.

I’m posting this question as deserializing and serializing JSON seems like it should be a pretty easy thing to do which I’m confident has already been addresses so rather than re-inventing the wheel I though I’d reach out to the Octopus team and wider community to see what the best practice is and how we should be dealing with this.

Thanks.

I’ve been able to make this work and while I’m confident there are better approaches which I encourage anyone to share, I thought I’d reply with what I’ve done to help point people in the right direction if they encounter a similar issues.

First and foremost, the main issue I was having is that I was referencing the namespace and not the assembly. Once I added a reference to the start of the script to the correct assembly “System.Web.Extensions” I was able to make the script compile.

I then proceeded to deserialize the object into a dynamic object as I’m not sure if it’s possible to define a complex type in a script such as this.

Heres a little sample script that I hope can be of help to somebody:

#r "System.Web.Extensions"
string json = "{ \"foo\": \"bar\", \"sampleArray\": [ \"value1\", \"value2\" ] }";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
dynamic deserializedObject = serializer.Deserialize<dynamic>(json);
Console.WriteLine($"The foo value: {deserializedObject["foo"]}");

Console.WriteLine("The sampleArray Items:");
foreach(dynamic arrayItem in deserializedObject["sampleArray"])
{
    Console.WriteLine($"    {arrayItem}");
}
1 Like

Hi,

Glad you solved it. You should be able to added classes to your script to deserialize to.

Another alternative is that we ship Newtonsoft.Json with Octopus, so you could load up that DLL. You can get the path the program install directory using the Octopus.Agent.ProgramDirectoryPath variable (doco.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.