JavaScript Object Notation(JavaScript 对象表示法);javascript
JSON是轻量级的文本数据交换格式;html
JSON独立于语言,具备自我描述性,更易理解;java
{ "site":[ {"name":"慕课网", "url":"www.imooc.com"}, {"name":"百度", "url":"www.baidu.com"}, {"name":"网易", "url":"www.163.com"} ] }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> <!--JS中将字符串转换成JSON--> var str = "{\"class_name\" : \"五年级一班\"}"; var json = JSON.parse(str); console.log(str); console.log(json); document.write("班级:" + json.class_name + "<br>"); <!--JS中将JSON转换成字符串--> var json2 = {"class_name" : "五年级二班"}; var str2 = JSON.stringify(json2); console.info(json2); console.info(str2); document.write(str2 + "<br>"); <!--JS中JSON对象初始化--> var json3 = {}; json3.class_name = "五年级三班"; console.log(json3); document.write("班级:" + json3.class_name); </script> </head> <body> </body> </html>
<b style="color: red;">Employee.java</b>json
package demo; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; public class Employee { @JSONField(serialize = false) //serialize属性:不对该成员序列化 private int empId; private String empName; @JSONField(name = "hiredate", format = "yyyy-MM-dd") //JSON注解,name属性:说明key,format属性:将日期格式化 private Date empIn; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public Date getEmpIn() { return empIn; } public void setEmpIn(Date empIn) { this.empIn = empIn; } public Employee(int empId, String empName, Date empIn) { super(); this.empId = empId; this.empName = empName; this.empIn = empIn; } @Override public String toString() { return "Employee [empId=" + empId + ", empName=" + empName + ", empIn=" + empIn + "]"; } }
<b style="color: red;">FastJsonSample.java</b>数组
package demo; import java.util.Calendar; import com.alibaba.fastjson.JSON; public class FastJsonSample { public static void main(String[] args) { Calendar c = Calendar.getInstance(); c.set(2019, 1, 24); Employee emp = new Employee(007, "星海", c.getTime()); String json = JSON.toJSONString(emp); //将Java对象转换成JSON字符串 System.out.println(json); Employee emp2 = JSON.parseObject(json, Employee.class); //将JSON字符串转换成Java对象 System.out.println(emp2); } }
控制台输出:ide
{"empName":"星海","hiredate":"2019-02-24"} Employee [empId=0, empName=星海, empIn=Sun Feb 24 00:00:00 CST 2019]
JSON.toJSONString(list)
将对象数组序列化JSON.parseArray(json, Employee.class)
将JSON数组反序列化