package com.gitee.sop.admin.common.jackson.convert.serde;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
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;

/**
 * <pre>
 * {@literal
 * 将数字类型转换成布尔
 *
 * 支持："["a", "b"]", "[1,2]", "1,2,3"
 *
 * @Listable
 * private String appList; // 返回给前端: "appList": ["xx"]
 *
 * }
 * </pre>
 *
 * @author 六如
 */
@Slf4j
public class ListSerializer extends JsonSerializer<Object> {


    @Override
    public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (value == null) {
            jsonGenerator.writeNull();
            return;
        }
        if (value instanceof String) {
            String str = (String) value;
            if (JSON.isValidArray(str)) {
                String json = String.valueOf(value);
                JSONArray array = JSON.parseArray(json);
                jsonGenerator.writeObject(array);
            } else {
                String[] split = str.split(",");
                jsonGenerator.writeObject(split);
            }
        } else {
            jsonGenerator.writeObject(value);
        }
    }

}
