Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON serializing an object with function parameter

I have this C# object:

var obj = new {
    username = "andrey",
    callback = "function(self) { return function() {self.doSomething()} (this) }"
}

I need to JSON serialize it to pass to the browser in ajax call. I use JavascriptSerializer, but it serializes to the following JSON:

{"username":"andrey", "callback": "function(self) { return function() {self.doSomething()} (this) }"}

but what I need is:

{"username":"andrey", "callback": function(self) { return function() {self.doSomething()} (this) }}
  • no quotes around function definition.

Right now, when the JSON object gets to the browser and is created, the 'callback' parameter is not a function but a string. Any idea how to fix it, preferably on the server side?

like image 294
Andrey Avatar asked Mar 21 '11 03:03

Andrey


1 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).

Example:

// set the property value using JRaw
var obj = new {
    username = "andrey",
    callback = new JRaw("function(self) { return function() {self.doSomething()} (this) }")
}
// and then serialize using the JsonConvert class
var jsonObj = JsonConvert.SerializeObject(obj);

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

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

like image 138
ryan Avatar answered Sep 25 '22 15:09

ryan