介绍
模板需求说明
开发中经常遇到前端传递过来的JSON串的转换,后端需要解析成对象,有解析成List的,也有解析成Map的。
依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.57</version>
</dependency>
解析模板
Response获取成String
public static String getResponseAsString(final HttpResponse response) {
try {
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (final ParseException e) {
throw new RuntimeException(e);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
JSON串解析
若已通过上述的Response方法转换成了String类型字符串为appsStr
。
JSON示例
JSON转换模板
try {
//获取第一级对象
JSONObject appsJSONObject = JSON.parseObject(appsStr).getJSONObject("apps");
//判断是否为空
if (appsJSONObject == null || appsJSONObject .size() <= 0) {
log.info("json has no apps");
}
//获取第二级对象数组JSONArray
JSONArray appJSONArray = appsJSONObject .getJSONArray("app");
//转换成二级对象字符串
String appStr = JSON.toJSONString(appJSONArray );
//字符串转换成第二级对象数组List
List<Map> appList = new ArrayList<>();
appList = JSONObject.parseArray(appStr, Map.class);
log.info("length: {}", appList.size());
} catch (Exception e) {
log.error(e.getMessage());
}
常用方法
转换bean对象
//其他方式获取到的Object对象
Object obj = xxx;
String responseStr = JSON.toJSONString(obj);
XXXXBean xxxxBean = JSON.parseObject(responseStr, XXXXBean.class);
转换Map
Object obj = xxx;
String responseStr = JSON.toJSONString(obj);
Map<String, Object> map = JSONObject.parseObject(responseStr,Map.class);
转换List
Object obj = xxx;
String responseStr = JSON.toJSONString(obj);
List<Map> mapList = JSON.parseArray(responseStr , Map.class);
List<XXXBean> xxxList = JSONObject.parseArray(responseStr, XXXBean.class);