com.qa.framework.library.base.JsonHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of smart-api-framework Show documentation
Show all versions of smart-api-framework Show documentation
Support web service api automaton test based on testng and httpclient
package com.qa.framework.library.base;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;
/**
* The type Json helper.
*/
public class JsonHelper {
/**
* The constant Error.
*/
public static final int Error = 0;
/**
* The constant ObjectJson.
*/
public static final int ObjectJson = 1;
/**
* The constant ArrayJson.
*/
public static final int ArrayJson = 2;
/**
* The constant Number.
*/
public static final int Number = 3;
/**
* The constant Str.
*/
public static final int Str = 4;
/**
* The constant phpArray.
*/
public static final int phpArray = 5;
/**
* 简单判断是否是json格式的字符串
*
* @param strJson the str json
* @return str 的类型
*/
public static int JudgeStringJson(String strJson) {
int flag = Error;
String str = strJson.trim();
if (str.startsWith("{") && str.contains(":") && str.endsWith("}")) {
flag = ObjectJson;
return flag;
}
if (str.startsWith("[{") && str.endsWith("}]")) {
flag = ArrayJson;
return flag;
}
if (str.startsWith("[") && str.endsWith("]")) {
flag = phpArray;
return flag;
}
if (str.matches("\\d*")) {
flag = Number;
return flag;
} else
return flag = Str;
}
/**
* 简单判断是否是json格式的字符串
*
* @param str the str
* @return the boolean
*/
public static boolean BooleanJudgeStringJson(String str) {
return str.startsWith("{") && str.contains(":") && str.endsWith("}") || str.startsWith("[") && str.endsWith("]");
}
/**
* Get json object string map. 将json转换成map
*
* @param jsonStr the json str
* @return the map
*/
public static Map getJsonMapString(String jsonStr) {
Map map = new HashMap();
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
Iterator it = jsonObject.keys();
while (it.hasNext()) {
String key = (String) it.next();
Object value = getObject(jsonObject.get(key).toString());
map.put(key, value);
}
return map;
}
/**
* Gets object.
*
* @param str the str
* @return the object
*/
public static Object getObject(String str) {
int type = JudgeStringJson(str);
switch (type) {
case 1: //如果返回的格式符合 {}, 则返回一个map
return getJsonMapString(str);
case 2: //如果返回的格式符合[{}], 则返回一个List
List