需求:最终存入数据库的格式如下
[{“optionId”:67,“nextQuestionSource”:“library”,“nextQuestionId”:5},{“optionId”:68,“nextQuestionSource”:“subject”,“nextQuestionId”:6}]
1. 数据库字段类型:varchar
2. 表对应的实体类:用JSONArray接收
3. JSON对应的实体类:
4. 最后别忘记xml中要调typeHandler进行格式转换:
5. 核心部分:
前端传参(List)
Java代码
List<NextDetail> list = example.getNextDetails();
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));
entity.setNextDetails(jsonArray);
super.updateById(entity);
6. 效果图:
7. 注意:
JSONArray在Java中的格式是带有双引号的,如下所示
"nextDetail":"[{"optionId":67,"nextQuestionSource":"library","nextQuestionId":5},{"optionId":68,"nextQuestionSource":"subject","nextQuestionId":6}]"
所以千万不要忘记进行格式转换,不然会报错的哦 ^ ^
附录
1. JSONArray转为List
JSONArray nextDetails = qsQuestion.getNextDetails(); //数据库
List<NextDetail> list = JSON.parseArray(nextDetails.toJSONString(), NextDetail.class);
2. List转为JSONArray
List<NextDetail> list = example.getNextDetails(); //前端传参
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));