Why String "\"[]\"" is a valid json?

172 views Asked by At

Why fastjson and Jackson both judge the string "\"[]\"" a valid JSON?

@Test
public void validJSON() {
    String jsonString1 = "\"[]\"";
    System.out.println("fastjson: " + JSON.isValid(jsonString1));

    ObjectMapper objectMapper = new ObjectMapper();
    boolean flag = false;
    try {
        JsonNode jsonNode1 = objectMapper.readTree(jsonString1);
        flag = true;
    } catch (Exception e) {
        flag = false;
    }
    System.out.println("jackjson: " + flag);
}

result:

fastjson: true
jackjson: true

I want to know why "\"[]\"" is a valid JSON string.

1

There are 1 answers

7
Chaosfire On BEST ANSWER

Because the example boils down to - "literary whatever you want here". Your variable jsonString1 holds the value - "[]" (the quotation marks are part of the json!). The specification says that (almost) anything enclosed in double quotes is a valid string, the rest should be escaped to be part of the string. Check this as well.

From the specification (2.5. Strings):

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks.

So, the value is a string and a valid json.