「Spring MVC」 Jacksonで@JsonFilterのサンプルコード
Javaコード
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
public class CustJsonSerializer {
static final String DYNC_INCLUDE = “DYNC_INCLUDE";
static final String DYNC_FILTER = “DYNC_FILTER";
ObjectMapper mapper = new ObjectMapper();
@JsonFilter(DYNC_FILTER)
interface DynamicFilter {
}
@JsonFilter(DYNC_INCLUDE)
interface DynamicInclude {
}
/**
* @param clazz
* @param include
* @param filter
*/
public void filter(Class<?> clazz, String include, String filter) {
if (clazz == null) return;
if (include != null && include.length() > 0) {
mapper.setFilterProvider(new SimpleFilterProvider().addFilter(DYNC_INCLUDE,
SimpleBeanPropertyFilter.filterOutAllExcept(include.split(“,"))));
mapper.addMixIn(clazz, DynamicInclude.class);
} else if (filter !=null && filter.length() > 0) {
mapper.setFilterProvider(new SimpleFilterProvider().addFilter(DYNC_FILTER,
SimpleBeanPropertyFilter.serializeAllExcept(filter.split(“,"))));
mapper.addMixIn(clazz, DynamicFilter.class);
}
}
public String toJson(Object object) throws JsonProcessingException {
return mapper.writeValueAsString(object);
}
}
class SampleJson {
public void main(String args[]) {
CustJsonSerializer cft= new CustJsonSerializer();
cft.filter(Article.class, “id,name", null);
String include = cft.toJson(new Article());
cft= new CustJsonSerializer();
cft.filter(Article.class, null, “id,name");
String filter = cft.toJson(new Article());
System.out.println(“message include: " + include);
System.out.println(“message filter: " + filter);
}
}