Serialize as an object using json.net

I want some properties to be serialized as "objects", not strings. For instance.

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

The def class is as follows:

public class handlers {

    public string OnClickHandler;
    public string OnMouseOutHandler;

}

Currently it looks like:

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

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

Edit:

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

clean up first:

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

and then usually call jQuery bind

 $elem.bind(this.handlers);

Accepting Dave's answer as the nearest.

+3
2

, JSON ( JSON.parse(), ).

, :

// 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 name.
var json = '{"onClickHandler": "clickEventHandler"}'

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

window[handlerMappings.onClickHandler]();
+1

JSON . JSON ( ). JSON , , (. ).

javascript-, JSON. , , () eval .

+2

Source: https://habr.com/ru/post/1781332/


All Articles