I am attempting to send a javascript function over json in .Net and I am having trouble serializing the object.
The javascript library Highcharts uses the following function on their json object to customize the chart tooltip.
tooltip: {
formatter: function() {
var s;
if (this.point.name) { // the pie chart
s = ''+
this.point.name +': '+ this.y +' fruits';
} else {
s = ''+
this.x +': '+ this.y;
}
return s;
}
},
I am attempting to use the popular Json.NET library using an anonymous type to create such object but all my efforts serialize to a string in the end. Any help is appreciated. Thanks!
I like the answer from ObOzOne, but it can be a little simpler by just using the WriteRawValue. For example:
public class FunctionSerializer : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(string));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
string valueAsString = Convert.ToString(value);
if (!string.IsNullOrWhiteSpace(valueAsString))
writer.WriteRawValue(valueAsString);
}
}
And then on your property that you want to serialize:
[JsonConverter(typeof(FunctionSerializer))]
public string HideExpression { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With