简体   繁体   中英

Serialize as object using json.net

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

{"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.

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.

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]();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM