Tất cả setting mặc định của JsonParser được định nghĩa trong enum JsonParser.Feature. Dùng isEnabled(feature) kiểm tra feature có bật không.
Cú pháp
public static enum JsonParser.Feature extends Enum<JsonParser.Feature>
boolean isEnabled(JsonParser.Feature feature)
Ví dụ liệt kê tất cả feature
import com.fasterxml.jackson.core.*;
import java.io.*;
public class JsonParserSettingsTest {
public static void main(String[] args) throws IOException {
String json = "[{\"name\":\"Adithya\",\"age\":\"30\"},{\"name\":\"Ravi\",\"age\":\"35\"}]";
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(json);
System.out.println("JsonParser Default Settings:");
for (JsonParser.Feature feature : JsonParser.Feature.values()) {
System.out.println(feature.name() + ": " + parser.isEnabled(feature));
}
}
}
Output (Jackson 2.15 defaults)
AUTO_CLOSE_SOURCE: true
ALLOW_COMMENTS: false
ALLOW_YAML_COMMENTS: false
ALLOW_UNQUOTED_FIELD_NAMES: false
ALLOW_SINGLE_QUOTES: false
ALLOW_UNQUOTED_CONTROL_CHARS: false
ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER: false
ALLOW_NUMERIC_LEADING_ZEROS: false
ALLOW_NON_NUMERIC_NUMBERS: false
ALLOW_MISSING_VALUES: false
ALLOW_TRAILING_COMMA: false
STRICT_DUPLICATE_DETECTION: false
IGNORE_UNDEFINED: false
INCLUDE_SOURCE_IN_LOCATION: true
Giải thích các Feature quan trọng
| Feature | Mặc định | Mô tả |
|---|---|---|
| ALLOW_COMMENTS | false | Cho phép /* */ và // comment trong JSON (non-standard) |
| ALLOW_UNQUOTED_FIELD_NAMES | false | Cho phép field name không có quotes: {name:"value"} |
| ALLOW_SINGLE_QUOTES | false | Cho phép single quote: {'name':'value'} |
| ALLOW_TRAILING_COMMA | false | Cho phép trailing comma: [1,2,], {a:1,} |
| ALLOW_NUMERIC_LEADING_ZEROS | false | Cho phép số leading zero: 0123 (octal-like) |
| STRICT_DUPLICATE_DETECTION | false | Phát hiện duplicate field name trong object |
| IGNORE_UNDEFINED | false | Bỏ qua property không có setter/field (deserialize) |
Tùy chỉnh Settings
JsonFactory factory = new JsonFactory()
.enable(JsonParser.Feature.ALLOW_COMMENTS)
.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
JsonParser parser = factory.createParser(jsonString);
Lưu ý
- Settings này áp dụng cho **parser** (read). Writer settings nằm ở
JsonGenerator.Feature. - Bật các feature non-standard (comments, single quotes) có thể giảm performance và interoperability.
AUTO_CLOSE_SOURCE=truetự đóng input source khi parser close - cẩn thận nếu muốn reuse stream.