All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.k7g.alloy.core.objectmapper.ExpandFlagEnumSerializer Maven / Gradle / Ivy

package cn.k7g.alloy.core.objectmapper;

import cn.k7g.alloy.annotation.ExpandFlag;
import cn.k7g.alloy.core.ext.FlagCode;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

@Slf4j
public class ExpandFlagEnumSerializer extends JsonSerializer {
    private ExpandFlag expandFlag;

    public ExpandFlagEnumSerializer(ExpandFlag expandFlag) {
        this.expandFlag = expandFlag;
    }

    @Override
    public void serialize(Object v, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        Map val = new HashMap<>();
        Set set = Optional.ofNullable((Set) v).orElse(new HashSet<>());
        try {
            Class value = this.expandFlag.value();
            Method valuesMethod = value.getMethod("values");
            FlagCode[] enums = (FlagCode[]) valuesMethod.invoke(null);
            for (FlagCode item : enums) {
                val.put(item.name(), set.contains(item));
            }
            jsonGenerator.writeObject(val);
        } catch (Exception e) {
            log.error("ExpandFlagEnumSerializer error", e);
        }
    }
}