Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a function as a parameter in json using C#

I am trying to create the json needed to create an object in jQuery using C#. The json needed is

{
    title: 'title text',
    upperVal: 40,
    lowerVal: 5,
    mouseover: function() { return 'difference ' + (upperVal - lowerVal); }
}

The first few elements were simple enough. I created a class to represent the object, JSObj, and then run this through JavascriptSerializer.Serialize()

public class JSObj {
    public string title { get; set; }
    public int upperVal { get; set; }
    public int lowerVal { get; set; }
}

This works fine for the first few attributes, but I don't have a clue how to return the correct mouseover function.

EDIT: The code provided is just sample code because the structure of the json I'm actually using is a bit more complicated. I'm using HighCharts, and one of the config options that I really need to use requires a function, even though they are not really valid json ( http://www.highcharts.com/ref/#tooltip--formatter ) so unfortunately I can't avoid the problem

like image 688
Jordan Wallwork Avatar asked Jul 12 '11 11:07

Jordan Wallwork


2 Answers

I was trying to accomplish something similar. In my case I was using MVC Razor syntax trying to generate a json object with a function passed in using the @<text> syntax.

I was able to get the desired output using the Json.net library (using JsonConvert and JRaw). http://james.newtonking.com/projects/json/help/html/SerializeRawJson.htm

Example:

public class JSObj
{
    public string Title { get; set; }
    public int UpperVal { get; set; }
    public int LowerVal { get; set; }
    public object MouseOver
    {
        get
        {
            // use JRaw to set the value of the anonymous function
            return new JRaw(string.Format(@"function(){{ return {0}; }}", UpperVal - LowerVal));
        }
    }
}

// and then serialize using the JsonConvert class
var obj = new JSObj { Title = "Test", LowerVal = 4, UpperVal = 10 };
var jsonObj = JsonConvert.SerializeObject(obj);

That should get you the json object with the function (instead of the function in a string).

{"Title":"Test","UpperVal":10,"LowerVal":4,"MouseOver":function(){ return 6; }}

Post: How to serialize a function to json (using razor @<text>)

like image 110
ryan Avatar answered Oct 09 '22 10:10

ryan


from JSON format definition here http://json.org/ it is clear that you cannot have functions in JSON.

define your function elsewhere in application and call it explicitly.

any kind of hack to support functions in JSON is bad practice as it conflicts with purpose of JSON as "lightweight data-interchange format". you can't interchange functions as they cannot be understood by anything else except javascript.

like image 40
keymone Avatar answered Oct 09 '22 10:10

keymone