json是一种与语言无关的数据交换的格式,使用Json的格式与解析方便的可以表示一个对象信息,json有两种格式:①对象格式:{“key1”:obj,“key2”:obj,“key3”:obj…}、②数组/集合格式:[obj,obj,obj…]。
1.对象格式
{
"birthday": "2019-02-03",
"lastUpdate": "2019-02-03 10:08:02"
"code": 200,
"msg": "新增成功",
"data": null
}
注意key与String类型value都需要加双引号
2.数组/集合格式
["张珊","李四","王五","小麻子"]
3.实体、JSON互转
/**JSON字符串->实体类**/
//单实体
R resultR = JSONObject.parseObject(jsonString,R.class);
//json数组
Object businessDemand = getData("businessDemand");
String s = JSONArray.toJSONString(businessDemand);
List<BusinessDemand> businessDemandList = JSONArray.parseArray(s, BusinessDemand.class);
/**实体转json字符串**/
//jeckson方式:
R resultR = (R)pjp.proceed();
String resultSerializble = new ObjectMapper().writeValueAsString(resultR);
//fastJson方式:
String s = JSON.toJSONString(resultR);
4.案例:
@Test
@DisplayName("项目立项导出测试")
void testProjectItemExport() throws IOException, XmlException {
ItemExportVO itemExportVO = ItemExportVO.builder()
.build();
String s = "{\"plProjectMainId\":\"1597493182549983232\",\"plProjectAttribute\":\"1\",\"plProjectName\":\"小陶测试质量计划全推\",\"plProjectNo\":\"adsfdsgd-23543\"}";
JSONObject jsonObject = JSONObject.parseObject(s);
String toJSONString = JSON.toJSONString(jsonObject);
itemExportVO = JSON.parseObject(toJSONString, ItemExportVO.class);
R result = itemQuery.projectItemExport(itemExportVO,response);
assertEquals(200,result.getCode(),"testProjectItemExport异常");
}
@Test
@DisplayName("项目立项列表导出测试")
void projectItemListExport() throws IOException {
String s = "[\"1584868462696595456\",\"1585095770044891136\",\"1585803532714377216\"]";
List<String> itemListIds = JSON.parseArray(s, String.class);
R result = itemQuery.projectItemListExport(itemListIds,response);
assertEquals(200,result.getCode(),"projectItemListExport异常");
}