package com.changhu.support.mybatisplus.handler.global.json;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.util.Set;

/**
 * author: luozhun
 * desc: 将 mysql json 映射成 list
 * createTime: 2023/10/30 15:50
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({Set.class})
public class SetTypeHandler extends AbstractJsonTypeHandler<Set<Object>> {

    public SetTypeHandler(Class<?> type) {
        super(type);
    }

    @Override
    public Set<Object> parse(String json) {
        if (!JSON.isValid(json)) {
            return null;
        }
        return new TypeReference<Set<Object>>() {
        }.parseObject(json);
    }

    @Override
    public String toJson(Set<Object> obj) {
        return JSON.toJSONString(obj);
    }

}
