package com.cpop.core.strategy.json;

import com.cpop.common.utils.StringUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.node.*;
import lombok.NoArgsConstructor;

import java.io.IOException;

/**
 * 反序列化时 将数组转为逗号拼接  ["0","1","2"] -> "0","1","2"
 *
 * @author Lynn
 * @date 2022/11/8 14:36
 */
@NoArgsConstructor
public class ArrayToStringDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
        if (treeNode instanceof IntNode) {
            return ((IntNode) treeNode).asText();
        } else if (treeNode instanceof LongNode) {
            return ((LongNode) treeNode).asText();
        } else if (treeNode instanceof DoubleNode) {
            return ((DoubleNode) treeNode).asText();
        } else if (treeNode instanceof ArrayNode) {
            //字符串数组，会多出两个引号，需要手动去除
            return StringUtils.replace(StringUtils.join((ArrayNode) treeNode, ","), "\"", "");
        } else if (treeNode instanceof TextNode) {
            return ((TextNode) treeNode).asText();
        }
        return "";
    }
}

