Search code examples
javajsonmongodbmongodb-javamongo-java-driver

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. For example a given key within the parent JSON can have an integer or a string value. In some cases it can also be another JSON string. When trying to use the JSON.parse() method from the mongo-java-driver library, I came across this behaviour -

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

The above code prints the value of o as 45.55

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

The above code throws a com.mongodb.util.JSONParseException

Why do both the code snippets not behave in the same way?


Solution

  • 45.55 is a valid JavaScript literal pertaining to the number with that value.

    product is not a valid JavaScript literal. "product" is. If you changed your second example to:

    String val = "\"product\"";
    

    ... it would work as you expect.