Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Xử lý lỗi khi deserialize JSON trong Java (Jackson)

Interface DeserializationProblemHandler cho phép handle error recoverable khi deserialize (unknown property, missing field, type mismatch...). Override handleUnknownProperty().

Cú pháp

public boolean handleUnknownProperty(DeserializationContext ctxt, 
    JsonParser p, JsonDeserializer<?> deserializer, 
    Object beanOrClass, String propertyName) throws IOException

Ví dụ: Bỏ qua unknown property (return true = continue)

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.*;

public class DeserializationErrorTest {
    public static void main(String[] args) throws Exception {
        String jsonString = "{\"id\":\"101\",\"name\":\"Ravi Chandra\",\"address\":\"Pune\",\"salary\":\"40000\"}";
        
        ObjectMapper mapper = new ObjectMapper();
        // Đăng ký handler
        mapper.addHandler(new UnmarshallingErrorHandler());
        
        Customer customer = mapper.readValue(jsonString, Customer.class);
        System.out.println(customer);
    }
}

class UnmarshallingErrorHandler extends DeserializationProblemHandler {
    @Override
    public boolean handleUnknownProperty(DeserializationContext ctxt, 
            JsonParser jp, JsonDeserializer<?> deserializer, 
            Object beanOrClass, String propertyName) 
            throws IOException, JsonProcessingException {
        
        System.out.println("Property '" + propertyName + "' không tồn tại trong class '" 
            + beanOrClass.getClass().getName() + "'");
        
        return true; // true = ignore & continue, false = throw exception
    }
}

class Customer {
    private int id; private String name, address;
    // getters/setters/toString...
}

Output khi return true

Property 'salary' doesn't exist in class 'Customer'
Customer [id=101, name=Ravi Chandra, address=Pune]

Output khi return false (hoặc không đăng ký handler)

Property 'salary' doesn't exist in class 'Customer'
Exception: UnrecognizedPropertyException: Unrecognized field "salary" 
(not marked as ignorable: "id", "address", "name")

Các handler method khác

  • handleMissingProperty() - field required bị thiếu.
  • handleUnexpectedToken() - token type không mong đợi.
  • handleWeirdStringValue() - string value đặc biệt (NaN, Infinity).
  • handleWeirdNumberValue() - number value đặc biệt.
  • handleWeirdKey() - key không hợp lệ.

Alternative: Global config (không cần handler)

ObjectMapper mapper = new ObjectMapper();
// Bỏ qua unknown property global
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// Hoặc ignore null field
mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);

Best Practice

  • Dùng FAIL_ON_UNKNOWN_PROPERTIES = false cho API public (tolerant).
  • Dùng custom handler khi cần **logging, metrics, conditional logic** (VD: ignore field deprecated nhưng log warning).
  • Handler đăng ký qua mapper.addHandler() hoặc SimpleModule.