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數組反序列化