JavaWeb基础——JSON
一、JSON是什么?
JSON(JavaScript Object Notation)、轻量级数据交换格式。
JSON的后缀名:.json JSON的MINE类型:application/json
二、JSON的格式
以下为实际JSON举例(包含基本类型与数组类型等),理论不再赘述。
{
"name":"张三",
"id":1001,
"address":
[
{"pro":"anhui","city":"fuyang"},
{"pro":"jiangsu","city":"nanjing"}
],
"bool":true
}
关于jsonPath,参考:https://www.cnblogs.com/weilunhui/p/3857366.html
三、如何遍历JSON
简单JSON对象的遍历:
1.obj.attr
2.obj["attr"]
3.使用 attr in json 进行遍历:
// 遍历简单json对象
function traverseJsonSimpleObj(){
var jsonObj = {"name": "kevin", "age": 27, "sex": "男", "city": "shenzhen"};
for(var key in jsonObj){
var html = "<p>"
html += (key + ' : ' + jsonObj[key]);
html += "</p>";
$("#out").append(html);
}
}
遍历json数组
function traverseJsonArray(){
var jsonArray = [{"name": "kevin", "age": 27, "sex": "男", "city": "shenzhen"},
{"name": "kevin2", "age": 28, "sex": "男", "city": "beijing"}];
//alert('JSON.stringify(jsonArray) = ' + JSON.stringify(jsonArray));
for(var i=0; i<jsonArray.length; i++){
var jsonObj = jsonArray[i];
for(var key in jsonObj){
var html = "<p>"
html += (key + ' : ' + jsonObj[key]);
html += "</p>";
$("#out").append(html);
}
$("#out").append("-----------------------------------------------------");
}
}
当然,可以简写为:
var json = [{dd:'SB',AA:'东东',re1:123},{cccc:'dd',lk:'1qw'}];
for(var i=0,l=json.length;i<l;i++){
for(var key in json[i]){
alert(key+':'+json[i][key]);
}
}
后台直接通过springMVC等框架结合jackson,将JSON字符串放入javaBean中(属性与名称对应)(见springMVC章节)
【更新】:实际springMVC后台@ResponseBody时返回JSON时前台的解析方法:
后台返回数据形式:
示例1:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@RequestMapping(value = "findAll",method = RequestMethod.GET) @ResponseBody public List<SimpleMenuList> findAll(HttpServletResponse response){ List<SimpleMenuList> mlList = menuListService.findAll(); /*ObjectMapper mapper = new ObjectMapper(); String jsonfromList = mapper.writeValueAsString(mlList); System.out.println(jsonfromList);*/ //Map<String,Object> map = new HashMap<String,Object>(); // map.put("list", mlList); // 许跨域访问 response.setHeader("Access-Control-Allow-Origin", "*"); return mlList; }
示例2:
实体类:(单个属性,只为举例)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class AssociateWord { private String assoWord; public String getAssoWord() { return assoWord; } public void setAssoWord(String assoWord) { this.assoWord = assoWord; } }
返回List:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for (int i =0; i<5; i++) { AssociateWord aw = new AssociateWord(); String s = "关键字"+i; System.out.println(s); aw.setAssoWord(s); list.add(aw); } return list;
其他示例可参见SSM—CRUD随笔等(如返回map)
//获得全部菜单列表
function getMenuList(){
$.ajax({
type : "get",
url : "http://localhost:8080/jeesite/f/menu_list/menuList/findAll",
success : function(result) {
console.log(result);
var jsonArray = eval(result);
alert("后台返回的菜单列表:"+jsonArray);
alert("数组长度:"+jsonArray.length);
//此处遍历点单列表
for(var i=0; i<jsonArray.length; i++){
var jsonObj = jsonArray[i];
for(var key in jsonObj){
alert(key + ' : ' + jsonObj[key]);
}
}
}
});
}
【更新】:jQuery each遍历JSON数组:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
{
"code": 100,
"msg": "操作成功",
"map": {
"pageInfo": {
"pageNum": 1,
"pageSize": 5,
"size": 5,
"startRow": 1,
"endRow": 5,
"total": 502,
"pages": 101,
"list": [
{
"empId": 1,
"empName": "Alan",
"gender": "M",
"email": "1001@qq.com",
"dId": 1,
"department": {
"deptId": 1,
"deptName": "宣传部"
}
},
{
"empId": 2,
"empName": "Bob",
"gender": "F",
"email": "1002@qq.com",
"dId": 2,
"department": {
"deptId": 2,
"deptName": "测试部"
}
},
{
"empId": 3,
"empName": "ed0b9",
"gender": "M",
"email": "ed0b9@qq.com",
"dId": 1,
"department": {
"deptId": 1,
"deptName": "宣传部"
}
},
{
"empId": 4,
"empName": "167b5",
"gender": "F",
"email": "167b5@qq.com",
"dId": 1,
"department": {
"deptId": 1,
"deptName": "宣传部"
}
},
{
"empId": 5,
"empName": "2fd6c",
"gender": "M",
"email": "2fd6c@qq.com",
"dId": 1,
"department": {
"deptId": 1,
"deptName": "宣传部"
}
}
],
"prePage": 0,
"nextPage": 2,
"isFirstPage": true,
"isLastPage": false,
"hasPreviousPage": false,
"hasNextPage": true,
"navigatePages": 5,
"navigatepageNums": [
1,
2,
3,
4,
5
],
"navigateFirstPage": 1,
"navigateLastPage": 5,
"lastPage": 5,
"firstPage": 1
}
}
}
对上述JSON遍历如下:(result即为JSON)
//解析员工数据
function build_emps_table(result){
//员工数据
var emps = result.map.pageInfo.list;
//使用jQuery遍历数组,遍历的是取出来的json数组,可以通过开发工具查看JSON结构
$.each(emps,function(idx,item){
//使用jQuery生成各列
var empIdTd = $("<td></td>").append(item.empId);
var empNameTd = $("<td></td>").append(item.empName);
//三目运算符处理性别
var genderTd = $("<td></td>").append(item.gender=="M"?"男":"女");
var emailTd = $("<td></td>").append(item.email);
var deptName = $("<td></td>").append(item.department.deptName);
});
}