JSON语法规则
数据由键(key)/值(value)描述,由逗号分隔
大括号代表一个完整的对象,拥有多个键/值对
中括号保存数组,多个对象之间使用逗号分隔
Javascript 访问JSON对象
JSON与字符串互相转换
JSON.parse()方法将字符串转换为JSON对象
JSON.stringify()方法将JSON对象转换为字符串
var jsonStr = '{"userName": "tiu","userAge": 26,"isMale": true}';
var json = JSON.parse(jsonStr);
var str = JSON.stringify(json);
使用JSON全局对象,不过比较可惜的是IE8以下的版本没有这个对象,如果不考虑兼容IE8一下版本的话JSON全局对象是个很有用的东西
FastJSON应用
FastJSON的介绍与下载安装
Java的JSON工具包还有FastJson、Jackson、Gson、Json-lib
www.github.com 搜索 fastjson 下载就行了
FastJson对象的序列化与饭序列化
package com.imooc.json; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; public class Employee { private String ename; private Integer employeeNo; private String job; @JSONField(serialize=false)//对某个属性不进行序列化 private String department; private Double saraly; @JSONField(format="yyyy-MM-dd HH:mm:ss") private Date entryTime;
public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public Integer getEmployeeNo() { return employeeNo; } public void setEmployeeNo(Integer employeeNo) { this.employeeNo = employeeNo; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public Double getSaraly() { return saraly; } public void setSaraly(Double saraly) { this.saraly = saraly; } public Date getEntryTime() { return entryTime; } public void setEntryTime(Date entryTime) { this.entryTime = entryTime; } }
package com.imooc.json; import java.util.Calendar; import com.alibaba.fastjson.JSON; public class Sample { public static void main(String[] args) { Employee emp = new Employee(); emp.setEname("李东"); emp.setEmployeeNo(4733); emp.setJob("java工程师"); emp.setDepartment("研发部"); emp.setSaraly(15000d); Calendar c = Calendar.getInstance(); c.set(2020, 9, 16, 20, 9); emp.setEntryTime(c.getTime()); //Fastjson中提供了json对象,完成对象与Json的字符串相互转换 String str = JSON.toJSONString(emp); System.out.println(str); //转换json对象 Employee employee = JSON.parseObject(str,Employee.class); System.out.println(employee.getClass()); } }
FastJSON对象数组序列化与反序列化