Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize as object using json.net

I want certain properties to be serialized as 'objects' and not strings. E.g.

{"onClickHandler": OnClickHandler, "onMouseOut": OnMouseOutHandler}

The class def is like this:

public class handlers {

    public string OnClickHandler;
    public string OnMouseOutHandler;

}

Currently it comes out as:

handlers: {"onClickHandler": "OnClickHandler", "onMouseOut": "OnMouseOutHandler"}

As you can guess, these are client side event handlers and correspond to javascript functions defined elsewhere. By emitting them within quotes, they are not interpreted as functions but as literal strings.

Edit:

Taking a cue out of Dave's answer, figured out a way:

first a little bit of scrubbing:

for (var handler in this.handlers) {
   if(window[this.handlers[handler]])
        this.handlers[handler] = window[this.handlers[handler]];
};

and then call jQuery bind normally

 $elem.bind(this.handlers);

Accepting Dave's answer as that is closest.

like image 254
Mrchief Avatar asked Jan 01 '26 08:01

Mrchief


2 Answers

JSON does not support representing functions. JSON consists of arrays of values, and objects (containing variables). Values in JSON can only be strings, numbers, objects or arrays (see the linked page for nice grammar diagram).

What you're after is javascript code, not a JSON object. If you're wanting to emit a reference to a function defined elsewhere, you may have to (shudder) use eval to execute it.

like image 88
developmentalinsanity Avatar answered Jan 03 '26 20:01

developmentalinsanity


As someone else mentioned, that wouldn't be valid JSON anyway (which precludes you from using JSON.parse(), among other potential drawbacks).

If your event handler functions are defined in the global window scope, you could call them like this:

// This is equivalent to defining window.clickEventHandler or
//  window['clickEventHandler'] as a function variable.
function clickEventHander() {
  // Magic.
}

// Valid JSON, using strings to reference the handler's name.
var json = '{"onClickHandler": "clickEventHandler"}'

// You might be using eval() or a framework for this currently.
var handlerMappings = JSON.parse(json);

window[handlerMappings.onClickHandler]();
like image 35
Dave Ward Avatar answered Jan 03 '26 22:01

Dave Ward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!