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

Chuyển Bean thành JSON loại trừ field dùng JsonConfig (JSON-lib)

JsonConfig.setExcludes(String[]) loại trừ các field theo tên khi serialize bean → JSON. JSON-lib đã cũ, khuyến nghị Jackson/Gson.

Cú pháp

public void setExcludes(String[] excludes)

Ví dụ: Exclude "age" và "address"

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

public class BeanToJsonExcludeTest {
    public static void main(String[] args) {
        Student student = new Student("Raja", "Ramesh", 35, "Madhapur");
        
        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"age", "address"}); // Loại trừ 2 field
        
        JSONObject obj = JSONObject.fromObject(student, config);
        System.out.println(obj.toString(3));
    }
    
    static class Student {
        private String firstName, lastName, address;
        private int age;
        // constructor, getters...
    }
}

Output

{
  "firstName": "Raja",
  "lastName": "Ramesh"
}

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

ObjectMapper mapper = new ObjectMapper();

// 1. @JsonIgnore - static (trên field/getter)
public class Student {
    @JsonIgnore private int age;
    @JsonIgnore private String address;
}

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

// 3. SimpleBeanPropertyFilter - programmatic
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.serializeAllExcept("age", "address");
FilterProvider filters = new SimpleFilterProvider().addFilter("excludeFilter", filter);
String json = mapper.writer(filters).writeValueAsString(student);

// 4. View-based - @JsonView (xem bài @JsonView)

// 5. PropertyFilter functional (Jackson 2.12+)
mapper.configOverride(Student.class)
      .setFilterId("excludeFilter"); // combine với FilterProvider

Lưu ý

  • setExcludes dùng tên **property** (JavaBean property name: bỏ get/set, lowercase first letter), không phải field name.
  • JSON-lib **deprecated**. Jackson cung cấp nhiều cách linh hoạt hơn: annotation, filter, view, config override.
  • Exclude field có annotation @JsonIgnore là cách phổ biến nhất, rõ ràng nhất.