package org.jeecg.common.api.serializer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;

@NoArgsConstructor
public class StringToArraySerializer extends JsonSerializer<String> {

    @Override
    public void serialize(String jsonStr, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (StringUtils.isNotBlank(jsonStr)) {
            try {
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                String[] strArray = new String[jsonArray.size()];
                for (int i = 0; i < jsonArray.size(); i++) {
                    strArray[i] = jsonArray.getString(i);
                }
                jsonGenerator.writeArray(strArray, 0, strArray.length);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}