How to detect trailing garbage using Jackson ObjectMapper

前端 未结 3 936
旧时难觅i
旧时难觅i 2021-01-20 00:43

Say I have a class

class A {
    public int x;
}

Then a valid json can be parsed as follows:

ObjectMapper mapper = new Obje         


        
3条回答
  •  盖世英雄少女心
    2021-01-20 01:05

    The main thing to do is to create a JsonParser first, separately, then call ObjectMapper.readValue() passing that parser, and THEN call nextToken() once more and verify it returns null (instead of non-null value, or throw exception).

    So, something like

    JsonParser jp = mapper.getFactory().createParser(jsonSource);
    try {
        Value v = mapper.readValue(jp, Value.class);
        if (jp.nextToken() != null) {
            //throw some exception: trailing garbage detected
        }
        return v;
    } finally {
        jp.close();
    }
    

    Note: This is for Jackson 2.x. For Jackson 1.x, use getJsonFactory().createJsonParser() instead of getFactory().createParser().

提交回复
热议问题