Site icon Ryadel

Serialize a string value without quotes in ASP.NET with Json.NET

dir2json - a PHP CLI script to output the contents of a folder tree into a JSON object

Today I was playing with Tabulator, a great open-source interactive table JavaScript library which I've already talked about a few times in the past (our Tabulazer Extension for Google Chrome is strongly based on it).

Such library requires some JavaScript in order to work, such as the following example:

As you can see, when inizializing the Tabulator object we need to pass an array of columns (see the tabledata variable in the above example); such array is basically an array of JSON objects with some basic properties that helps the library to render the actual table, such as name, width, and so on.

The problem

In my ASP.NET Core projects I often end-up generating the Tabulator's JavaScript code dinamically from the back-end using the Json.NET library by Newtonsoft - which I actually like more than the built-in alternative offered by the framework (System.Text.Json) for a number of reasons that I've explained in this post. Such library works great, but in order to create valid JSON it automatically quotes both the object names and the values (if they are strings).

This basically means that such JSON object:

gets serialized in the following way:

Such serialization standard is absolutely fine for Tabulator for almost any possible scenario... except when the value is a JavaScript function, variable or reference.

In other words, if we want to assign a JavaScript function to the formatter parameter in the following way...

... we would end up with the following:

which won't be executed correctly by the Tabulator script, thus ending up in a format error.

The solution

Luckily enough I've stumbled upon this StackOverflow's answer that helped me to develop the following class:

As we can see, this is a custom JsonConverter (based upon the JsonConverter base class available from the Newtonsoft.Json namespace) that allows to output a string value without quotes.

Once implemented, such converter can be used to decorate the property of the ViewModel that hosts the JavaScript values, in the following way:

When serialized, such class will produce the following output...

... which is precisely what we need.

DISCLAIMER: Be wary that the JSON serialized using the JavaScriptValueConverter shown above won't be valid JSON and might likely crash or have unexpected results if de-serialized, executed or otherwise used in other contexts: however, it can be a decent workaround whenever you have to pass JS functions, variables or references through a JS script.

Conclusion

That's it, at least for now: I hope that this simple yet effective workaround will help other developers to achieve what they want without losing too much time or having to re-engineer their whole process.

Exit mobile version