在我们测试工作中,特别是接口测试,在写接口测试平台过程中很多Responce都是json格式,但是对于java,json的字串转为map更加方便我们对于数据提取。
对比python,py可以直接转换dict,很方便。但是对于对java不是很熟悉的同学,有一个工具类可以直接将json转换为Map一定是很实用的。
1 import java.util.*; 2 3 import javax.management.RuntimeErrorException; 4 5 import org.apache.commons.lang3.StringUtils; 6 7 import com.google.gson.*; 8 9 public class JsonToMapUtils { 10 /** 11 * 判断是否为json 12 * 13 * @param json 14 * @return 15 */ 16 public static boolean isjson(String json) { 17 if (StringUtils.isBlank(json)) { 18 return false; 19 } 20 try { 21 new JsonParser().parse(json); 22 return true; 23 } catch (Exception e) { 24 // TODO: handle exception 25 // throw new RuntimeException(json+":不是json格式"); 26 return false; 27 } 28 } 29 30 /** 31 * 将Map转成json 32 * 33 * @param map 34 * @return 35 */ 36 public static String mapToJson(Map<String, Object> map) { 37 Gson gson = new Gson(); 38 return gson.toJson(map, Map.class); 39 } 40 41 /** 42 * 依据json字符串返回Map对象 43 * 44 * @param json 45 * @return 46 */ 47 public static Map<String, Object> jsontoMap(String json) { 48 Gson gson = new Gson(); 49 return JsonToMapUtils.toMap(JsonToMapUtils.parseJson(json)); 50 } 51 52 /** 53 * 获取JsonObject 54 * 55 * @param json 56 * @return 57 */ 58 public static JsonObject parseJson(String json) { 59 JsonParser parser = new JsonParser(); 60 JsonObject jsonObj = parser.parse(json).getAsJsonObject(); 61 return jsonObj; 62 } 63 64 /** 65 * 将JSONObjec对象转换成Map-List集合 66 * 67 * @param json 68 * @return 69 */ 70 public static Map<String, Object> toMap(JsonObject json) { 71 Map<String, Object> map = new HashMap<String, Object>(); 72 Set<Map.Entry<String, JsonElement>> entrySet = json.entrySet(); 73 for (Iterator<Map.Entry<String, JsonElement>> iter = entrySet.iterator(); iter.hasNext();) { 74 Map.Entry<String, JsonElement> entry = iter.next(); 75 String key = entry.getKey(); 76 Object value = entry.getValue(); 77 if (value instanceof JsonArray) 78 map.put((String) key, toList((JsonArray) value)); 79 else if (value instanceof JsonObject) 80 map.put((String) key, toMap((JsonObject) value)); 81 else 82 map.put((String) key, value); 83 } 84 return map; 85 } 86 87 /** 88 * 将JSONArray对象转换成List集合 89 * 90 * @param json 91 * @return 92 */ 93 public static List<Object> toList(JsonArray json) { 94 List<Object> list = new ArrayList<Object>(); 95 for (int i = 0; i < json.size(); i++) { 96 Object value = json.get(i); 97 if (value instanceof JsonArray) { 98 list.add(toList((JsonArray) value)); 99 } else if (value instanceof JsonObject) { 100 list.add(toMap((JsonObject) value)); 101 } else { 102 list.add(value); 103 } 104 } 105 return list; 106 } 107 }