I have a package called ChartJSCore which generates the required JavaScript for creating Chart.js charts in a web application. For the most part the JS for this is essentially JSON so this works by serializing chart objects using Newtonsoft which automatically quotes both the object name and value. However, some of the properties of the chart object are JS functions and these can’t be quoted as otherwise they won’t be executed correctly by the Chart.js script.
To output a string value without quotes I created a Json converter based on this answer from StackOverflow.
public class PlainJsonStringConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.Value;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue((string)value);
}
}
This can then be used to decorate the required property like so.
public class Tick
{
[JsonConverter(typeof(PlainJsonStringConverter))]
public string Callback { get; set; }
}
Although this isn’t valid JSON, it is necessary for passing functions through to Chart.js and other related JS scripts and so seems like the least bad option.
An example of this in action can be found here.
0 Comments