1.Json的格式

其实json就是对象。源生的js代码并没有类的概念。对象救就是object。对象有自己的属性,也可以有自己的方法。json是一种轻量级的存储和交换信息的语言。他有自己的格式。

较为简单的json。里面只有简单的对象,key+value的形式

var CellInfo = {"CellId":     document.getElementById("CellId").value,"UEAmount":     document.getElementById("UE value").innerText,"BearAddDel":     document.getElementById("bearvalue").innerText,"UEAttachDe":    document.getElementById("attachvalue").innerText,"TotalDLTP":   document.getElementById("dlvalue").innerText,"TotalULTP":   document.getElementById("ulvalue").innerText,};

每个元素之间用逗号隔开。调用每个key的值可用语句。例如:CellInfo.UEAmunt,就可取出其中的值。

较为复杂的json。里面包含了对象。

var UEGroup1 = {"UEAmount": ua[1],"DBR1": {"DLPackageSize": DS[1],"ULPackageSize": US[1],"DLTP": DP[1],"ULTP": UP[1],"QCI": QCI[0]},"DBR2": {"DLPackageSize": DS[2],"ULPackageSize": US[2],"DLTP": DP[2],"ULTP": UP[2],"QCI": QCI[1]},"DBR3": {"DLPackageSize": DS[3],"ULPackageSize": US[3],"DLTP": DP[3],"ULTP": UP[3],"QCI": QCI[2]}};

例如这个UEGroup1,里面的元素不仅有简单的key+value,还包含了三个对象。对象里的元素用{}括起来,彼此之间用逗号隔开。想具体访问某个元素的值也是通过逐层key,例如:UEGrooup1.DBR1.DLPackageSize

动态的往json只增加元素,增加对象。

前面说的几个都是静态的,提前写好的。那如果临时想加一个元素,例如在Cellinfo这个json中相加一个number的元素:

CellInfo.number=10;

对于往json中添加对象。例如我们想把Cellinfo和UEGroup1这两个object作为两个元素加入到另外一个大的json中:

 var PETInfo = {};//声明了一个空的对象var CellInfo = {"CellId":   document.getElementById("CellId").value,"UEAmount":     document.getElementById("UE value").innerText,"BearAddDel":     document.getElementById("bearvalue").innerText,"UEAttachDe":    document.getElementById("attachvalue").innerText,"TotalDLTP":   document.getElementById("dlvalue").innerText,"TotalULTP":   document.getElementById("ulvalue").innerText,};str_CellInfo = JSON.stringify(CellInfo);//将CellInfo转为字符串对象PETInfo.CellInfo=str_CellInfo;//在PETInfo中添加名为Cellinfo的属性,并赋值

2.json的发送

json写好后,发送给后台。至于后台怎么处理数据我们不关心。发送json的函数如下:

function post(path, params, method) {method = method || "post";var form = document.createElement("form");form.setAttribute("method", method);form.setAttribute("action", path);for (var key in params) {if (params.hasOwnProperty(key)) {var hiddenField = document.createElement("input");hiddenField.setAttribute("type", "hidden");hiddenField.setAttribute("name", key);hiddenField.setAttribute("value", params[key]);form.appendChild(hiddenField);}}document.body.appendChild(form);form.submit();
}

参数分别是后台的地址,变量,方法。变量就是我们自己写好的json,方法默认为post。例如我们想发刚刚的PETInfo

$.post('http://10.140.160.64:3012/users/ueinfo', PETInfo);

数据的发送、并获取结果的实例:

需求描述:用户填写一系列的输入框,前端获取数据,封装成json并发送给服务器,服务器会返回一个返回值,表示状态。前端需要展示这个内容提示客户。

function sendBook(){var Book={"openstackIP":document.getElementById("openstackIP").value,"RAPName":document.getElementById("RAPName").value,"RAPVer":document.getElementById("ver").value,"OAMIP":document.getElementById("OAMIP").value};//json封装用户输入的数据$.post('http://10.140.160.64:3012/servers/env/book', Book)//调用post传输数据.done((resp) => {//传输后获取服务器的返回值alert(resp);//展示返回值// window.location.href = 'Environment-List.html';//选择性界面跳转});
}

3.json在本地的存储

存储数据有很多方法。这里我用的是localStorage。localStorage与cookie的区别如下:

① cookie在浏览器与服务器之间来回传递。
sessionStorage和localStorage不会把数据发给服务器,仅在本地保存

②数据有效期不同:
cookie只在设置的cookie过期时间之前一直有效,即使窗口或浏览器关闭。
sessionStorage:仅在当前浏览器窗口关闭前有效。
localStorage  始终有效,长期保存。

③cookie数据还有路径的概念,可以限制cookie只属于某个路径下。
存储大小也不同,cookie数据不能超过4k,sessionStorage和localStorage 虽然也有存储大小的限制,但比cookie大得多,可以达到5M或更大。

④ 作用域不用
sessionStorage不在不同的浏览器窗口中共享;
localStorage在所有同源窗口中都是共享的;
cookie也是在所有同源窗口中都是共享的;

WebStorage 支持事件通知机制,可以将数据更新的通知发送给监听者。Web Storage 的 api 接口使用更方便。

用localstage存储json的实例:

str_PETInfo=JSON.stringify(PETInfo);//将json转为字符串对象
window.localStorage.setItem("PET",str_PETInfo);//存入本地,该json的key为PET

将json取出来:

var PET=JSON.parse(window.localStorage.getItem("PET"));//将字符串转化为json
var CellInfo=JSON.parse(PET.CellInfo);//json中的Cellinfo对象转化为json

4.多个Json的处理

例子描述:网上订餐系统。在后台数据库分为商家表、骑手表、订单表、顾客表。那现在呢是要绘制地图,需要三者的全部信息。后台将信息发送,前台如何接受多个json并打包成易于使用的完整Json

后台代码:

@WebServlet(name="/CustomerWaiting",urlPatterns= {"/WEB-UI/pages/CustomerWaiting"})
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.setCharacterEncoding("UTF-8");response.setContentType("text/xml;character=utf-8");//获取当前正在使用系统的用户idCacheService cache=new CacheService();String name=cache.Getname();//根据用户id从数据库中取出状态为等待的订单String hql="FROM Food food WHERE food.state like '%waiting%' AND name=?";HibernateService hs=new HibernateService();RiderService rs = new RiderService();List<Food> list =hs.FoodSearch(hql, name);List<Rider> riderslist = new ArrayList();List<Owner> ownerlist = new ArrayList();for(int i = 0; i < list.size(); i++) {Food food = list.get(i);String shopname = food.getShopname();//根据订单中的骑手名属性,取出对应的负责配送的骑手的全部信息Rider rider = rs.SearchByRiderName(food.getRidername());//根据订单中商店名的属性,取出对应的商家的全部信息Owner owner = rs.SearchOwnerByShopname(shopname);riderslist.add(rider);ownerlist.add(owner);}//用JSONArray将list封装成一条条的数组,装进jsonJSONArray jb = JSONArray.fromObject(list);JSONArray jb2 = JSONArray.fromObject(riderslist);JSONArray jb3 =JSONArray.fromObject(ownerlist);//转换成String发送给前端response.getWriter().write(jb.toString());response.getWriter().write(jb2.toString());response.getWriter().write(jb3.toString());}

后端总结:这样做的好处是,现在每个列表都有着一一对应的关系。比如在订单表里第一条,包含订单内容a、骑手001、商家002等等。那在骑手表里的第一条就是骑手001的全部信息,在商家表里的第一条就是商家002的全部信息。

前端接收:

var mapNote = {}; //制作每组数据的Json
var mapcontent2 = []; //数组形式,用来加入每一条json
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {if (this.readyState == 4 && this.status == 200) {// Typical action to be performed when the document is ready:  //接收String,将三个Json分离var json = xhttp.responseText;// console.log(json);for (var i = 0; i < json.length; i++) {var ch = json.charAt(i);if (ch == ']') {var food = json.substring(0, i + 1);var json2 = json.substring(i + 1);console.log("=====food");console.log(food);break;}}for (var j = 0; j < json2.length; j++) {var ch2 = json2.charAt(j);var ch3 = json2.charAt(j + 1);if (ch2 == ']' && ch3 == '[') {var map = json2.substring(0, j + 1);var owner = json2.substring(j + 1);console.log("=====riders");console.log(map);console.log("=====owners");console.log(owner);break;}}//将String转换成Jsonvar note = JSON.parse(food);var riders = JSON.parse(map);var owners = JSON.parse(owner);//填写订单信息到表格for (var key in note) {var table = document.getElementById("FoodWait");var tr = table.insertRow(1);var button = "<button type=\"button\" data-toggle=\"modal\" data-target=\"#myModal\" class=\"btn btn-danger btn-circle\"onclick=\"Operate(this,'t2','delete')\"><i class=\"fa fa-times\"></i></button> <button type=\"button\" data-toggle=\"modal\" data-target=\"#myModal2\" class=\"btn btn-primary btn-circle\" onclick=\"Operate(this,'t3','update')\"><i class=\"fa fa-pencil\"></i></button> ";var mapbutton = "<button onclick=\"test(this,mapcontent2,'FoodWait')\" type=\"button\" data-toggle=\"modal\" data-target=\"#myModal3\" class=\"btn btn-primary btn-circle\"><i class=\"glyphicon glyphicon-map-marker\"></i></button>";tr.insertCell(0).innerHTML = button;tr.insertCell(1).innerText = note[key].id;tr.insertCell(2).innerText = note[key].time;tr.insertCell(3).innerText = note[key].pretime;tr.insertCell(4).innerText = note[key].name;tr.insertCell(5).innerText = note[key].phone;tr.insertCell(6).innerText = note[key].place;tr.insertCell(7).innerText = note[key].food;tr.insertCell(8).innerText = owners[key].shopname;tr.insertCell(9).innerHTML = mapbutton;//绘图所需完整的JSonvar mapcon = {"orderid": note[key].id,"customerX": note[key].customerX,"customerY": note[key].customerY,"ridername": riders[key].name,"riderphone": riders[key].phone,"riderX": riders[key].riderX,"riderY": riders[key].riderY,"totalordernum": riders[key].totalordernum,"score": riders[key].average,"shopname": owners[key].shopname,"shopX": owners[key].shopX,"shopY": owners[key].shopY,"shopphone": owners[key].phone,"place": owners[key].place};//将mapcon转成str格式,并装入数组mapcontent2var strmapcon = JSON.stringify(mapcon);mapcontent2.push(strmapcon);}console.log("=====mapInfo");console.log(mapcontent2);addTR();}};
xhttp.open("GET", "CustomerWaiting", true);
xhttp.send();

因为在后台已经实现了一一对应的关系,那么在前端就可以在一个循环内,将三方的数据拼成一个较为完整的数组。那么这个数组已经无限接近当初从后台取出List封装成JsonArray的格式了,我们看下前端的conslog

根据对应关已经将零散的三方数据拼成了一个数组(mapcontent2)。那么在传参的时候也是用数组的形式,但在转换为Json的时候要额外注意:

传参调用:

button onclick="test(this,mapcontent2,'FoodWait')"

将数组转换成Json

 //将数组类型转化为JsonmapNote2 = JSON.parse('['+mapcontent2+']');

json的格式、存储与发送以及多个Json的处理相关推荐

  1. json string 格式_GO小知识之如何做JSON美化

    经常有些小知识想分享出来,但又构不成体系,一直觉得文章形式发出不太合适.准备以 "知乎想法" 分享出来,但发现代码展示不太友好.还是发文章吧,该类分享将以 "小知识&qu ...

  2. 如何以类似JSON的格式打印圆形结构?

    本文翻译自:How can I print a circular structure in a JSON-like format? I have a big object I want to conv ...

  3. 使用filbeat从kafka中消费json格式日志并发送到ElasticSearch

    环境 filbeat 7.10 kafka 2.1 elasticsearch 7.4.2 windows 10 需求描述 Java程序生产Json格式的日志发送到kafka中,再由filebeat从 ...

  4. 在python中使用json格式存储数据

    在python中使用json格式存储数据 代码如下: import jsonlist1 = [{'A': [1, 2, 3, 4, 5, 6], 'B': [3, 4, 5, 6, 7]},{'C': ...

  5. Ajax 发送json格式数据以及发送文件(FormData)和自带的序列化组件: serializers

    前后端传输数据的编码格式(contentType) get请求数据就是直接放在url?后面的 url?usernmae=junjie&password=123... 可以向后端发送post请求 ...

  6. Mysql中使用json格式存储数据好吗?

    在最近的一次项目开发过程中,在数据表设计阶段,对是否用json格式存储某些数据我们产生了分歧.以往项目中对此点比较随意,导致数据表中有些json格式数据体积很大,层次很深,我担心这会降低数据查询和解析 ...

  7. 文件路径json格式存储

    项目需要以json格式存储指定文件目录结构,如需求如下所示: 简要思路,遍历指定目录结构,存储在list中,然后,取出每一条路径结构,进行json格式化, 与已有json格式路径对象相加. 生成jso ...

  8. JSON数据表示格式简介(JavaScript对象表示法)

    [1] JSON简介     > JSON全称 JavaScript Object Notation     > 类似于JS中对象的创建的方法     > JSON和XML一样,都是 ...

  9. JS高级——JSON、数据存储学习笔记

    在目前的开发中,JSON是一种非常重要的数据格式,它并不是编程语言,而是一种可以在服务器和客户端之间传输的数据格式. JSON的全称是JavaScript Object Notation(JavaSc ...

最新文章

  1. 分享几个 Pyecharts 技巧,助你画出更直观/炫酷的图表
  2. 免费学习AI公开课:打卡、冲击排行榜,还有福利领取
  3. Sharding-JDBC教程:Spring Boot整合Sharding-JDBC实现数据分表+读写分离
  4. 第十六届智能汽车竞赛AI视觉组分赛区数据集发布
  5. 奇数码问题(逆序对)
  6. python 周末大作业之2
  7. 一篇文章全方位了解:static main final
  8. React之JSX入门
  9. mysql语句engin_MySQL必会的SQL语句
  10. 读取properties资源文件中的参数
  11. python工资这么高为什么不学-为什么学Python的人越来越多?
  12. html点击按钮 重新加载页面或者跳转页面实现
  13. 学习总结 for循环语句的应用
  14. Windows中MySQL主从数据库搭建(三)
  15. ArcGIS 计算地块容积率
  16. 死亡之ping (ping of death)
  17. Oracle数据库基本操作(windows 本地环境)
  18. Could not read JSON: Can not deserialize instance of java.lang.String[] out of VALUE_STRING token
  19. javascript的生命周期
  20. 火狐下载文件名乱码问题

热门文章

  1. 09 智慧桥/ 艾摩君
  2. 灵遁者油画作品《最美丽的女孩》
  3. 分享5个良心好用的PC软件,免费无广告
  4. java a null b a_下列不属于Java关键字的是()。A.thisB.superC.finallyD.NULL
  5. 使用Java编写一个简单的 JFrame登陆注册界面(一)
  6. 月薪30K的软件测试简历怎么包装?
  7. OGRE CEGUI LAYOUT
  8. 百度地图(icon,zIndex)
  9. c++ 判断硬件是否支持opengl_【译】OpenGL 教程:二维图形绘制
  10. L1正则化和L2正则化讲解