001/*
002 *    Copyright 2024-2025, Warm-Flow (290631660@qq.com).
003 *
004 *    Licensed under the Apache License, Version 2.0 (the "License");
005 *    you may not use this file except in compliance with the License.
006 *    You may obtain a copy of the License at
007 *
008 *       https://www.apache.org/licenses/LICENSE-2.0
009 *
010 *    Unless required by applicable law or agreed to in writing, software
011 *    distributed under the License is distributed on an "AS IS" BASIS,
012 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *    See the License for the specific language governing permissions and
014 *    limitations under the License.
015 */
016package org.dromara.warm.plugin.json;
017
018import org.dromara.warm.flow.core.json.JsonConvert;
019import org.dromara.warm.flow.core.utils.MapUtil;
020import org.dromara.warm.flow.core.utils.StringUtils;
021import org.noear.snack.ONode;
022
023import java.util.HashMap;
024import java.util.Map;
025
026/**
027 * snack:map和json字符串转换工具类
028 *
029 * @author warm
030 */
031public class JsonConvertSnack implements JsonConvert {
032
033    /**
034     * 不可删除,为了在spi加载时候,发下不存在snack3依赖包,触发异常不加载此实现类
035     */
036    private static final ONode oNode = new ONode();
037
038    /**
039     * 将字符串转为map
040     * @param jsonStr json字符串
041     * @return map
042     */
043    @Override
044    public Map<String, Object> strToMap(String jsonStr) {
045        return StringUtils.isEmpty(jsonStr) ? new HashMap<>() : ONode.deserialize(jsonStr);
046    }
047
048    /**
049     * 将map转为字符串
050     * @param variable map
051     * @return json字符串
052     */
053    @Override
054    public String mapToStr(Map<String, Object> variable) {
055        if (MapUtil.isNotEmpty(variable)) {
056            return ONode.serialize(variable);
057        }
058        return MapUtil.isEmpty(variable) ? null : ONode.serialize(variable);
059    }
060}