使用fastJson配置setSerializerFeatures

继承FastJon

public class Group3FastJson extends FastJson{
	
	private static Set<SerializerFeature> serializerFeatureSet = new LinkedHashSet<>();
	
	static {
		// FastJson默认SerializerFeature
		serializerFeatureSet.add(SerializerFeature.WriteDateUseDateFormat);
	}
	
	public static void setSerializerFeatures(SerializerFeature...  serializerFeatures) {
		if (serializerFeatures == null) {
			throw new IllegalArgumentException("serializerFeatures can not be null.");
		}
		
		for (SerializerFeature serializerFeature : serializerFeatures) {
			serializerFeatureSet.add(serializerFeature);
		}
	}
	
	public static FastJson getJson() {
		return new Group3FastJson();
	}
	
	@Override
	public String toJson(Object object) {
		// 优先使用对象级的属性 datePattern, 然后才是全局性的 defaultDatePattern
		String dp = datePattern != null ? datePattern : getDefaultDatePattern();
		if (dp == null) {
			return JSON.toJSONString(object);
		} else {
			return JSON.toJSONStringWithDateFormat(object, dp, serializerFeatureSet.toArray(new SerializerFeature[serializerFeatureSet.size()]));
		}
	}
}

继承FastJsonFactory

public class Group3FastJsonFactory extends FastJsonFactory{
	
	private static final Group3FastJsonFactory me = new Group3FastJsonFactory();
	
	public static Group3FastJsonFactory me() {
		return me;
	}
	
	@Override
	public Json getJson() {
		return new Group3FastJson();
	}
}

配置:

public void configConstant(Constants me) {		
        me.setJsonFactory(Group3FastJsonFactory.me());
        Group3FastJson.setSerializerFeatures(SerializerFeature.WriteMapNullValue, 
                                             SerializerFeature.WriteNullStringAsEmpty);	   
}


评论区

JFinal

2020-12-16 14:42

扩展代码很简洁,赞一个

steven_lhcb_9527

2020-12-16 14:52

我觉得应该用Optional代替null

风满楼

2020-12-16 17:26

@steven_lhcb_9527 就单纯一个判空动作也没后续调用别的,没必要Optional,而且Optional在这里也没用。