
com.hecloud.runtime.common.utils.JSONTools Maven / Gradle / Ivy
package com.hecloud.runtime.common.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hecloud.runtime.common.model.GenericResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
/**
* JSON工具类
*
* @author LoveinBJ
*/
public class JSONTools {
private static Logger logger = LoggerFactory.getLogger(JSONTools.class);
public static boolean isMap(String jsonString) {
try {
JSONObject.parseObject(jsonString, HashMap.class);
return true;
} catch (Exception e) {
logger.error("Param format exception:{}", e.getMessage());
return false;
}
}
public static GenericResult isJSON(String jsonString) {
if (StringUtils.isEmpty(jsonString)) {
return new GenericResult<>(false, "FORMAT ERROR!");
}
try {
JSONObject jsonObject = JSONObject.parseObject(jsonString, JSONObject.class);
return new GenericResult<>(true, "success", jsonObject);
} catch (Exception e) {
logger.error("Param format exception:{}", e.getMessage());
return new GenericResult<>(false, "FORMAT ERROR!");
}
}
public static GenericResult> isJSONArray(String jsonString) {
if (StringUtils.isEmpty(jsonString)) {
return new GenericResult<>(false, "FORMAT ERROR!");
}
try {
List list = JSONObject.parseArray(jsonString, JSONObject.class);
return new GenericResult<>(true, "success", list);
} catch (Exception e) {
logger.error("Param format exception:{}", e.getMessage());
return new GenericResult<>(false, "FORMAT ERROR!");
}
}
/**
* 获取json字符串对应的JSONObject对象
*
* @param jsonString json字符串
* @return 如果json字符串为空,或转换失败,返回null
*/
public static JSONObject isJSONObj(String jsonString) {
if (StringUtils.isNotEmpty(jsonString)) {
try {
return JSONObject.parseObject(jsonString, JSONObject.class);
} catch (Exception e) {
logger.error("Param format exception: {}", e.getMessage());
return null;
}
} else {
return null;
}
}
/**
* 功能:把Json数据格式字符串转换为JSonArray
*
* @param jsonString json字符串
* @return json数组
*/
public static JSONArray parseStr2JsonArray(String jsonString) {
if (StringUtils.isNotEmpty(jsonString)) {
try {
return JSONArray.parseArray(jsonString);
} catch (Exception e) {
logger.error("Param format exception: {}", e.getMessage());
return null;
}
} else {
return null;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy