杰克逊的JSON(2.5.0)验证没有按预期工作

时间:2015-02-20 15:21:06

标签: java json jackson

简单的测试用例:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public static void main(String[] args) throws Exception {
    String json = "1,2";
    ObjectMapper parser = new ObjectMapper();
    JsonNode rootNode = parser.readTree(json);

}

抛出异常:

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: 
Unexpected character (',' (code 44)): Expected space separating root-level values
at [Source: 1,2; line: 1, column: 3]

所有善良和花花公子,但如果我将String json更改为以下任何一项:

String json = "null,false";
String json = "[1,2,3,null,\"hello\"],false";
String json = "true,3";
String json = "true,{\"test\":3}";

没有抛出异常。

为何出现差异?

1 个答案:

答案 0 :(得分:4)

默认情况下,Jackson使用ReaderBasedJsonParser,在读取/启动要解析的JSON时,有明确的检查

switch (i) {
        case '"':
            _tokenIncomplete = true;
            t = JsonToken.VALUE_STRING;
            break;
        case '[':
            if (!inObject) {
                _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol);
            }
            t = JsonToken.START_ARRAY;
            break;
        case '{':
            if (!inObject) {
                _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol);
            }
            t = JsonToken.START_OBJECT;
            break;
        case ']':
        case '}':
            // Error: neither is valid at this point; valid closers have
            // been handled earlier
            _reportUnexpectedChar(i, "expected a value");
        case 't':
            _matchTrue();
            t = JsonToken.VALUE_TRUE;
            break;
        case 'f':
            _matchFalse();
            t = JsonToken.VALUE_FALSE;
            break;
        case 'n':
            _matchNull();
            t = JsonToken.VALUE_NULL;
            break;

        case '-':
            /* Should we have separate handling for plus? Although
             * it is not allowed per se, it may be erroneously used,
             * and could be indicate by a more specific error message.
             */
            t = _parseNegNumber();
            break;
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            t = _parsePosNumber(i);
            break;

从上面的代码中你可以看到它检查你提到的字符 - null,true,{,[,false等等。如果有任何匹配,它会返回有效的json标记。这就是为什么,如果你改变

String json = "true,3";

String json = "3,true";

它将再次抛出众所周知的异常。

请注意,还会检查以字母" n"开头的给定字符串,验证它是否与null匹配(对以&#34开头的字符串进行相同检查; t",& #34; F"。)

然后有趣的是_parsePosNumber(i)方法,它基本上调用_reportMissingRootWS来检查根 - 它显然会失败。

所以基本上如果json有效,它永远不会到达" failer" case,或者如果给定的字符串以" true"," false"," null"," [",&## 34; {","]","}"它也被认为是有效的json。

我认为此功能在Jackson non standard features列表中,因此上述格式被视为有效的JSON。