json序列化的奇怪之处
我正在使用自定义 JavaScriptConverter 来序列化两个对象。其中一个是对象列表,它工作得很好;另一个是单个对象。 我将两者序列化并将它们放入页面的源代码中。当我在浏览器中查看它们的 HTML 源代码时,我发现有效的看起来像这样:
var Object1 = '[{....}]';
而不起作用的看起来像这样:
var Object2 = '{...}';
当我运行 eval 时,它不适用于 Object2。我只是不明白为什么序列化不同,因为我对两者使用相同的原理;我显然做错了什么。如果您遇到类似问题或有建议,请告诉我。
谢谢。
I'm using a custom JavaScriptConverter to serialize two objects. One of them is a list of objects and it works just fine; the other one is a single object.
I serialize both and put them in the source code of the page. When I look at them HTML source in a browser, I see that the one that works looks like this:
var Object1 = '[{....}]';
while the one that doesn't work looks like this:
var Object2 = '{...}';
When I run an eval, it doesn't work with Object2. I'm just not seeing why the serialization is different since I'm using the same principal for both; I'm obviously doing something wrong. If you've run into a similar issue or have a suggestion, then please let me know.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您遇到了 Javascript 解析歧义。
而不是:
你需要:
在 Javascript 中,左大括号可以启动对象文字:
或块:
但是,块不能出现在表达式中,因此添加括号可以解决歧义。
You are running into a Javascript parsing ambiguity.
Instead of:
you need:
In Javascript, an open brace can start either an object literal:
or a block:
However, a block cannot appear in an expression, so adding the parentheses resolves the ambiguity.
规范第 12.4 节说:
这里讨论了许多解决方法/解决方案:
Section 12.4 of the spec says:
There are numerous workarounds/solutions discussed here:
没有什么奇怪的。在 JSON 中,您有用
{ ... }
表示的普通对象和用[{ ... }, { ... }, ... 表示的普通对象列表]
和 .因此,如果您的第二个对象不是列表,您就不能指望它会被序列化。如果您希望第二个对象包含在[]
中,您可以创建一个包含一个元素(即第二个对象)的列表,然后序列化该列表。There is nothing weird. In JSON you have normal objects which are denoted with
{ ... }
and lists of normal objects which are denoted with[{ ... }, { ... }, ...]
and . So if your second object is not a list you cannot expect it to be serialized as such. If you wanted your second object to be enclosed with[]
you could create a list containing one element which is the second object and then serialize this list.