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.google.gson.Gson; 019import com.google.gson.reflect.TypeToken; 020import org.dromara.warm.flow.core.json.JsonConvert; 021import org.dromara.warm.flow.core.utils.MapUtil; 022import org.dromara.warm.flow.core.utils.StringUtils; 023 024import java.lang.reflect.Type; 025import java.util.HashMap; 026import java.util.Map; 027 028/** 029 * fastjson:map和json字符串转换工具类 030 * 031 * @author warm 032 */ 033public class JsonConvertGson implements JsonConvert { 034 035 private static final Gson gson = new Gson(); 036 037 /** 038 * 将字符串转为map 039 * @param jsonStr json字符串 040 * @return map 041 */ 042 @Override 043 public Map<String, Object> strToMap(String jsonStr) { 044 if (StringUtils.isNotEmpty(jsonStr)) { 045 Type type = new TypeToken<Map<String, Object>>(){}.getType(); 046 return gson.fromJson(jsonStr, type); 047 } 048 return new HashMap<>(); 049 } 050 051 /** 052 * 将map转为字符串 053 * @param variable map 054 * @return json字符串 055 */ 056 @Override 057 public String mapToStr(Map<String, Object> variable) { 058 if (MapUtil.isNotEmpty(variable)) { 059 return gson.toJson(variable); 060 } 061 return null; 062 } 063 064}