smartcaveman smartcaveman - 18 days ago 7
C# Question

Why is there a JConstructor?

Json.NET defines a


This is confusing, because (to the best of my knowledge) constructors are not part of JSON. I double-checked the JSON spec and browsed 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)))


new ctorExample(
"prop1": 1,
"prop2": 2

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


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.