@JsonFilter 註解用於定義自訂篩選器來序列化 Java 物件。我們需要使用FilterProvider類別來定義過濾器並取得實際的過濾器實例。現在,透過將 FilterProvider 指派給 ObjectMapper 類別來設定篩選器。
@Target(value={ANNOTATION_TYPE,TYPE,METHOD,FIELD,PARAMETER}) @Retention(value=RUNTIME) public @interface JsonFilter
在下面的範例中,可以將customFilter 宣告為@JsonFilter 註解的參數,該註解僅提取名稱並過濾掉a 的其他屬性豆。
import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; public class JsonFilterAnnotationTest { public static void main(String args[]) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); FilterProvider filterProvider = new SimpleFilterProvider().addFilter("customFilter", SimpleBeanPropertyFilter.filterOutAllExcept("empName")); String jsonString = mapper.writer(filterProvider).writeValueAsString(new FilterBean()); System.out.println(jsonString); } } @JsonFilter("customFilter")<strong> </strong>class FilterBean { public int empId = 110; public String empName = "Raja Ramesh"; public String gender = "male"; }
{"empName":"Raja Ramesh"}
以上是@JsonFilter註解在Java中的重要性是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!