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 com.fasterxml.jackson.databind.ObjectMapper;
019import com.fasterxml.jackson.databind.type.TypeFactory;
020import org.dromara.warm.flow.core.exception.FlowException;
021import org.dromara.warm.flow.core.json.JsonConvert;
022import org.dromara.warm.flow.core.utils.MapUtil;
023import org.dromara.warm.flow.core.utils.StringUtils;
024import org.slf4j.Logger;
025import org.slf4j.LoggerFactory;
026
027import java.io.IOException;
028import java.util.HashMap;
029import java.util.Map;
030
031/**
032 * jackson:map和json字符串转换工具类
033 *
034 * @author warm
035 */
036public class JsonConvertJackson implements JsonConvert {
037
038    private static final Logger log = LoggerFactory.getLogger(JsonConvertJackson.class);
039
040    private static final ObjectMapper objectMapper = new ObjectMapper();
041    /**
042     * 将字符串转为map
043     * @param jsonStr json字符串
044     * @return map
045     */
046    @Override
047    public Map<String, Object> strToMap(String jsonStr) {
048        if (StringUtils.isNotEmpty(jsonStr)) {
049            try {
050                return objectMapper.readValue(jsonStr, TypeFactory.defaultInstance().constructMapType(Map.class, String.class, Object.class));
051            } catch (IOException e) {
052                log.error("json转换异常", e);
053                throw new FlowException("json转换异常");
054            }
055        }
056        return new HashMap<>();
057    }
058
059    /**
060     * 将map转为字符串
061     * @param variable map
062     * @return json字符串
063     */
064    @Override
065    public String mapToStr(Map<String, Object> variable) {
066        if (MapUtil.isNotEmpty(variable)) {
067            try {
068                return objectMapper.writeValueAsString(variable);
069            } catch (Exception e) {
070                log.error("Map转换异常", e);
071                throw new FlowException("Map转换异常");
072            }
073        }
074        return null;
075    }
076
077}