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

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

package cn.k7g.alloy.core.objectmapper;

import cn.k7g.alloy.annotation.AlloyContent;
import cn.k7g.alloy.expose.AlloyContentHandler;
import cn.k7g.alloy.ioc.SpringUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
/**
 * 序列化alloyContent
 * @author victor-wu
 * @date 2024年4月3日
 */
public class AlloyContentSerializer extends JsonSerializer {
    private AlloyContent alloyContent;
    private AlloyContentHandler alloyContentHandler;

    public AlloyContentSerializer(AlloyContent alloyContent) {
        this.alloyContent = alloyContent;
    }

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (o == null) {
            jsonGenerator.writeNull();
            return;
        }
        jsonGenerator.writeString(getHandler().encodeObject(o));
    }

    public AlloyContentHandler getHandler() {
        if (alloyContentHandler == null) {
            alloyContentHandler = SpringUtil.getBean(AlloyContentHandler.class);
        }
        if (alloyContentHandler == null) {
            // 不允许在初始化未完成的时候调用,对于mvc来说这不会触发
            throw new RuntimeException("系统尚未初始化完成");
        }
        return alloyContentHandler;
    }
}