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

Chuyển Bean thành JSON với Exclude Filter dùng JSON-lib (Java)

JsonConfig.setJsonPropertyFilter() cấu hình PropertyFilter tùy chỉnh để exclude field khi serialize bean → JSON. JSON-lib đã cũ, khuyến nghị Jackson/Gson.

Cú pháp

public void setJsonPropertyFilter(PropertyFilter jsonPropertyFilter)

Ví dụ: Exclude field non-String/Number

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

public class BeanToJsonExcludeFilterTest {
    public static void main(String[] args) {
        Student student = new Student("Sai", "Chaitanya", 20, "Hyderabad");
        
        JsonConfig config = new JsonConfig();
        config.setJsonPropertyFilter(new CustomPropertyFilter());
        
        JSONObject jsonObj = JSONObject.fromObject(student, config);
        System.out.println(jsonObj.toString(3));
    }
    
    static class Student {
        private String firstName, lastName, address;
        public int age;
        // constructor, getters...
    }
}

// Custom Filter: Chỉ giữ String và Number, loại bỏ kiểu khác
class CustomPropertyFilter implements PropertyFilter {
    @Override
    public boolean apply(Object source, String name, Object value) {
        // return true = FILTER OUT (loại bỏ)
        if (value == null) return true;
        if (Number.class.isAssignableFrom(value.getClass())) return false; // giữ Number
        if (String.class.isAssignableFrom(value.getClass())) return false; // giữ String
        return true; // loại bỏ type khác
    }
}

Output

{
  "firstName": "Sai",
  "lastName": "Chaitanya",
  "address": "Hyderabad",
  "age": 20
}

Tương đương với Jackson (Khuyến nghị)

// 1. @JsonIgnore - static exclude
public class Student {
    @JsonIgnore private String secret;
}

// 2. @JsonFilter - dynamic (xem bài @JsonFilter)

// 3. ObjectMapper config - global
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // exclude null
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

// 4. SimpleBeanPropertyFilter (programmatic)
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.serializeAllExcept("secret");
FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", filter);
String json = mapper.writer(filters).writeValueAsString(student);

Lưu ý

  • JSON-lib **unmaintained**, nhiều dependency, ít feature so với Jackson/Gson.
  • PropertyFilter.apply() return true = exclude, false = include (ngược trực giác).
  • Filter áp dụng cho **serialize**. Deserialize cần config riêng.