about 4 years ago

在結合Spring跟jackson之後,幾乎所有的物件幾乎都可以自動幫你變成json資料格式輸出,
雖然有@JsonIgnore可以註解掉某些不想輸出的欄位,但有的時候需要有的時候不需要的話就要靠自訂過濾器來輔助了

1.先來看我們主要回覆的物件,裡面有關聯請退款紀錄

Morder.java
@Entity
@Table(name = "MORDER", catalog = "payment", uniqueConstraints = @UniqueConstraint(columnNames = {
        "MERCHANTNUMBER", "TRANSNUMBER" }))
public class Morder implements java.io.Serializable {
    // Fields

    private String ordersn;
    private String merchantnumber;
    private String orgordernumber;
    private Long transnumber;
    private Integer orderamount;
    // 退款紀錄

    private Set<Morderrefund> morderrefunds = new HashSet<Morderrefund>(0);
    // 請款紀錄

    private Set<Morderdeposit> morderdeposits = new HashSet<Morderdeposit>(0);
    private Notify notify;
    // 其他略過

}

2.建立過濾器

MorderQueryFilter.java
import com.fasterxml.jackson.annotation.JsonFilter;

@JsonFilter("MorderQueryFilter")
public class MorderQueryFilter {
    //底下是不想被轉成json的物件名稱

    public static String[] ignorableFieldNames = { "morderdeposits", "morderrefunds" };
}

3.自訂輸出
原本你只需要像Spring與Jackson結合這篇將物件放入HashMap中讓他自動轉換,現在你必須透過ObjectMapper自己轉換好輸出

MorderController.java
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Object.class, MorderQueryFilter.class);
FilterProvider filters = new SimpleFilterProvider().addFilter("MorderQueryFilter",SimpleBeanPropertyFilter.serializeAllExcept(MorderQueryFilter.ignorableFieldNames));
ObjectWriter writer = mapper.writer(filters);
try {
    response.setContentType("text/html;charset=utf-8");
    OutputStream os = response.getOutputStream();
    os.write(writer.writeValueAsString(map).getBytes("utf-8"));
    os.flush();
    os.close();
} catch (Exception e) {
    log.error("", e);
}
← spring內設定檔加密 CentOS相關指令 →
 
comments powered by Disqus