得到一串json串之后,直接把json解析成map,然后调动公共入库方法进行存库操作
service层:保存单个json对象:{}
Map resultData = (Map)JSON.parse(result);
//对json内层的{}或者[]进行toString()
resultData.put("allLevelCount",resultData.get("allLevelCount")==null?null:resultData.get("allLevelCount").toString());
Map<String, Object> saveMap = new HashMap<>();
//表名
saveMap.put("tableName", "rec_bd_flow_nodeChildCount_data");
//需要保存的数据
saveMap.put("data", resultData);
//入库逻辑
flowMapper.saveData(saveMap);
service层:保存数组json对象:[{}]
List<Map> valueList = (List<Map>)JSON.parse(result);
if (CollectionUtils.isNotEmpty(valueList) && valueList.size() > 0){
for (Map map : valueList) {
//对json内层的{}或者[]进行toString()
map.put("linkStates",map.get("linkStates")==null? null:map.get("linkStates").toString());
map.put("baiduEvents",map.get("baiduEvents")==null?null:map.get("baiduEvents").toString());
}
Map<String, Object> saveMap = new HashMap<>();
//表名
saveMap.put("tableName", "rec_bd_flow_alarmList_data");
//取一个对象的key,作为insert SQL 的数据库字段名
saveMap.put("key", valueList.get(0).keySet().toArray());
//数据集合
saveMap.put("data", valueList);
//入库逻辑
flowMapper.saveDataList(saveMap);
Dao层
//json为单个对象:{}
int saveData(@Param("map") Map<String, Object> map);
//json为集合:[{}]
int saveDataList(@Param("map") Map<String, Object> map);
Mybatis
<!-- 使用#{}点位符时, 不要使用statementType="STATEMENT"声明 -->
<insert id="saveData" parameterType="java.util.HashMap">
insert into ${map.tableName} (
<foreach collection="map.data" item="value" index="key" separator=",">
`${key}`
</foreach>
, `paramId`
)
values (
<foreach collection="map.data" item="value" index="key" separator=",">
#{value}
</foreach>
)
</insert>
<insert id="saveDataList" parameterType="java.util.HashMap">
insert into ${map.tableName} (
<foreach collection="map.key" item="value" separator=",">
`${value}`
</foreach>
, `paramId`
)
values
<foreach collection="map.data" item="line" separator=",">
(
<foreach collection="line" index="key" item="value" separator=",">
#{value}
</foreach>
)
</foreach>
</insert>