Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send javascript function over json using Json.NET lib

Tags:

c#

.net

json.net

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!

like image 655
Diego Avatar asked Dec 17 '22 17:12

Diego


1 Answers

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; }
like image 51
Jamieson Rhyne Avatar answered Dec 19 '22 07:12

Jamieson Rhyne