基于Spring和Vue的Json应用
一、Java后台的json字符串转化
应用场景:
- ·json字符串转List/Object: 数据库中字段存储json字符串,或者接受前台的json字符串,按需转为实体类,插入分表
- · List/Object转json字符串: 查表后转化为json字符串传递给前台,或者插入总表中存储字符出的字段
注:Array和Object使用语法存在差异
1、json字符串转List/Object
(1)jsonArray
字符串样式:[{"属性1": value1, "属性2":value2}, {"属性1": value3, "属性2":value4}, ]
属性可包含jsonArray
java
public class FactoryCheckPlanItemJson {
private Long id;
private Long checkContents;
private String answer;
private List<Item> item;
}
String checkItemJsonString = "[\"id\":1,\"checkContent\":\"检查\",\"answer\":\"A\",\"item\":\"[{\"A\",\"health\"\"},{\"B\",\"unhealth\"\"}]\"]"//获取所有点位 使用json转换为任务项类型
List<FactoryCheckPlanItemJson> factoryCheckPlanItemsJson = JSON.parseArray(checkItemJsonString).toJavaList(FactoryCheckPlanItemJson.class);
(2) jsonObject
字符串样式:{"属性1": value1, "属性2":value2}
java
List<FactoryCheckPlanItemJson> factoryCheckPlanItemsJsonList = mapper.select();
String checkItemJsonString = JSONObject.toJSONString(factoryCheckPlanItemsJsonList);
2、List/Object转json字符串
// 适用于普通实体类和List
java
FactoryCheckPlanItemJson a = new FactoryCheckPlanItemJson();
JSONObject.toJSONString(factoryCheckPlanItemsJsonList)
二、Vue前台的json转化
应用场景:
·前台对后台传递的json字符串解析为object用于展示
·前台的表单为object, 提交后转化为json字符串传递到后台
注:Array和Object使用语法一样
1、jsonString转实体类
JSON.parse(jsonString)
Eg:
javascript
let questionOptions = []
if (response.data.checkItem) {
let tmp = JSON.parse(row.checkItem);
for (let key in tmp) {
let a = {
option: key, content: tmp[key]
}
questionOptions.push(a);
}
return questionOptions
}
2、实体类转jsonString
javascript
JSON.stringfy(list)
JSON.stringfy(object)