简体   繁体   English

JSON 解析字符串失败,但通过 Java 中的数字

[英]JSON parsing fails for string but passes for number in Java

I am writing a parser for incoming JSON data with no definite structure for the values within the JSON.我正在为传入的 JSON 数据编写一个解析器,对于 JSON 中的值没有明确的结构。 For example a given key within the parent JSON can have an integer or a string value.例如,父 JSON 中的给定键可以具有整数或字符串值。 In some cases it can also be another JSON string.在某些情况下,它也可以是另一个 JSON 字符串。 When trying to use the JSON.parse() method from the mongo-java-driver library, I came across this behaviour -在尝试使用 mongo-java-driver 库中的 JSON.parse() 方法时,我遇到了这种行为 -

String val = "45.55";
Object o = JSON.parse(val);
System.out.println(o);

The above code prints the value of o as 45.55上面的代码将o的值打印为 45.55

String val = "product";
Object o = JSON.parse(val);
System.out.println(o);

The above code throws a com.mongodb.util.JSONParseException上面的代码抛出一个com.mongodb.util.JSONParseException

Why do both the code snippets not behave in the same way?为什么两个代码片段的行为方式不同?

45.55 is a valid JavaScript literal pertaining to the number with that value. 45.55是与具有该值的数字有关的有效 JavaScript 文字。

product is not a valid JavaScript literal. product不是有效的 JavaScript 文字。 "product" is. "product"是。 If you changed your second example to:如果您将第二个示例更改为:

String val = "\"product\"";

... it would work as you expect. ...它会按您的预期工作。

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

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