Why is there a JConstructor?

夙愿已清 提交于 2019-12-01 14:20:18

问题


Json.NET defines a JConstructor type.

This is confusing, because (to the best of my knowledge) constructors are not part of JSON. I double-checked the JSON spec and browsed json.org but couldn't find anything. There also doesn't seem to be much documentation about this type anywhere on the web.

Because Json.NET is so widely used (it is even cosigned by Microsoft) I assume there has to be some reasonable motivation for including this representation in the object model. The problem is, any attempt on my part to determine that motivation is nothing but speculation.

I tested out the type and its serialization, and the apparent behavior is to just wrap JavaScript code such as new constructorName(...), e.g.:

new JConstructor("ctorExample", 
    new JValue("value"), 
    new JObject(
        new JProperty("prop1", new JValue(1)), 
        new JProperty("prop2", new JValue(2)))
        )
.ToString()

outputs

 new ctorExample( 
   "value", 
   { 
     "prop1": 1, 
     "prop2": 2 
   } 
 ) 

So, what is the JConstructor type intended to represent and why does it exist?


回答1:


Json.NET includes many features which are not part of JSON specification. In particular, it allows parsing some JSON files which are "officially" invalid. This includes unquoted properties, comments, constructors etc. It includes serialization of references and many other features. Some features, like comments or unquoted properties, can later become part of the standard.

JConstructor allows producing code to be used by JavaScript apps. Data serialized this way is invalid JSON, but valid JavaScript code. Such JSON files cannot be parsed using JSON.parse method, but eval will be able to handle them. In some cases it may be useful, it's probably bad practice though, mostly useful for backwards compatibility with existing JS scripts, so this is probably the reason it's not advertised.



来源:https://stackoverflow.com/questions/25351479/why-is-there-a-jconstructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!