简体   繁体   English

使用json.net序列化为对象

[英]Serialize as object using json.net

I want certain properties to be serialized as 'objects' and not strings. 我希望某些属性被序列化为“对象”而不是字符串。 Eg 例如

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

The class def is like this: 类def是这样的:

public class handlers {

    public string OnClickHandler;
    public string OnMouseOutHandler;

}

Currently it comes out as: 目前它出现为:

handlers: {"onClickHandler": "OnClickHandler", "onMouseOut": "OnMouseOutHandler"} 处理程序:{“onClickHandler”:“OnClickHandler”,“onMouseOut”:“OnMouseOutHandler”}

As you can guess, these are client side event handlers and correspond to javascript functions defined elsewhere. 您可以猜到,这些是客户端事件处理程序,并对应于其他地方定义的javascript函数。 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: 从Dave的回答中得到一个提示,想出了一个方法:

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 然后正常调用jQuery bind

 $elem.bind(this.handlers);

Accepting Dave's answer as that is closest. 接受Dave的回答是最接近的。

JSON does not support representing functions. JSON不支持表示函数。 JSON consists of arrays of values, and objects (containing variables). JSON由值数组和对象(包含变量)组成。 Values in JSON can only be strings, numbers, objects or arrays (see the linked page for nice grammar diagram). JSON中的值只能是字符串,数字,对象或数组(请参阅链接页面以获得很好的语法图)。

What you're after is javascript code, not a JSON object. 你所追求的是javascript代码,而不是JSON对象。 If you're wanting to emit a reference to a function defined elsewhere, you may have to (shudder) use eval to execute it. 如果您想要发出对其他地方定义的函数的引用,您可能必须(颤抖)使用eval来执行它。

As someone else mentioned, that wouldn't be valid JSON anyway (which precludes you from using JSON.parse(), among other potential drawbacks). 正如其他人提到的那样,无论如何都不是有效的JSON(这使你不能使用JSON.parse(),以及其他潜在的缺点)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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