package com.ff.weijinxiao.util.jsonfilter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ff.weijinxiao.util.JacksonJsonFilter;


public class CustomerJsonSerializer {
    ObjectMapper mapper = new ObjectMapper();
    JacksonJsonFilter jacksonFilter = new JacksonJsonFilter();

    /**
     * @param clazz   target type
     * @param include include fields
     * @param filter  filter fields
     */
    public void filter(Class<?> clazz, String include, String filter) {
        if (clazz == null) {
            return;
        }
        if (include != null && !include.equals("")) {
            jacksonFilter.include(clazz, include.split(","));
        }
        if (filter != null && !filter.equals("")) {
            jacksonFilter.filter(clazz, filter.split(","));
        }
        mapper.addMixIn(clazz, jacksonFilter.getClass());
    }

    public String toJson(Object object) throws JsonProcessingException {
        mapper.setFilterProvider(jacksonFilter);
        return mapper.writeValueAsString(object);
    }

    public void filter(Json json) {
        this.filter(json.type(), json.include(), json.filter());
    }

    /**
     * 用于测试自定义是否起作用
     *
     * @param args
     * @throws JsonProcessingException
     */
    public static void main(String args[]) throws JsonProcessingException {
        CustomerJsonSerializer customerJsonSerializer = new CustomerJsonSerializer();
        /*customerJsonSerializer.filter(Staff.class, "id", null);

        String include = customerJsonSerializer.toJson(new Staff());

        customerJsonSerializer = new CustomerJsonSerializer();
        // 设置转换 Test 类时，过滤掉 name
        customerJsonSerializer.filter(Staff.class, null, "id");

        String filter = customerJsonSerializer.toJson(new Staff());

        System.out.println("include: " + include);
        System.out.println("filter: " + filter);*/
    }
}
