一、Java中Json格式的判定
首先关于Json格式的判定,这里展示常用的两种方法,
1、对象解析法
即将需判断的字符串解析是否正常,这种校验比较严格,也比较准确;
public static boolean pdJson(String pdStr) {
try {
JSONObject obj= JSON.parseObject(pdStr);
return true;
} catch (Exception e) {
return false;
}
}
2、字符判定法
即通过判断首尾字母是否为{}或[]确认字符串是否为Json格式;
public static boolean pdJSON(String pdStr) {
if (StringUtils.isNotBlank(pdStr)) {
pdStr = pdStr.trim();
if (pdStr.startsWith("{") && pdStr.endsWith("}")) {
return true;
} else if (pdStr.startsWith("[") && pdStr.endsWith("]")) {
return true;
}
}
return false;
}
二、FastJson中各类型的转换
1、String转换为Map
Map mapp = Json.parseObject(zhStr, Map.class);
2、Map转换为String
zhStr =JsonUtil.toJSONString(mapp);
3、String转换为Json对象
JSONObject obj = JSONObject.parseObject(zhStr);
4、Json对象转换为String
String zhStr=jsonObject1.toString(obj);
5、Map转换为Json对象
JSONObject json = new JSONObject(mapp);
6、Json对象转换为Map
Map mapp = JSONObject.parseObject(obj, Map.class);