Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีดู Default Settings ของ JSONParser ด้วย Jackson ใน Java

การตั้งค่า default ทั้งหมดของ JSON Parser สามารถแสดงได้ผ่าน JsonParser.Feature enumeration เมธอด JsonParser.Feature.values() จะคืนค่าทุก features ที่มีสำหรับ JSONParser แต่ว่า feature ใด enabled หรือ disabled สำหรับ parser ตัวใดตัวหนึ่ง สามารถตรวจสอบได้ด้วยเมธอด isEnabled() ของ JsonParser

Syntax

public static enum JsonParser.Feature extends Enum<JsonParser.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 jsonFactory = new JsonFactory();
        JsonParser jsonParser = jsonFactory.createParser(json);
        
        for (JsonParser.Feature feature : JsonParser.Feature.values()) {
            System.out.println(feature.name() + ":" + jsonParser.isEnabled(feature));
        }
    }
}

ผลลัพธ์ (Output) - Default Settings

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

คำอธิบาย Features สำคัญ

Feature Default คำอธิบาย
AUTO_CLOSE_SOURCE true ปิด input source อัตโนมัติเมื่อ parser ปิด
ALLOW_COMMENTS false อนุญาต comments ใน JSON (/* */, //)
ALLOW_UNQUOTED_FIELD_NAMES false อนุญาต field names ไม่มี quotes
ALLOW_SINGLE_QUOTES false อนุญาต single quotes แทน double quotes
ALLOW_TRAILING_COMMA false อนุญาต trailing comma ใน arrays/objects
STRICT_DUPLICATE_DETECTION false ตรวจจับ duplicate keys ใน object
IGNORE_UNDEFINED false ข้าม properties ที่ไม่รู้จัก

การเปลี่ยนแปลง 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);

สรุป

JsonParser.Feature enum ให้การเข้าถึงและตรวจสอบ parser settings ทั้งหมด สามารถ enable/disable features ได้ผ่าน JsonFactory เพื่อรองรับ JSON variants (JSON5, YAML-like, etc.) หรือความเข้ากันได้กับระบบเก่า