JSON
JavaScript Object Notation(JavaScript 对象表示法);
JSON是轻量级的文本数据交换格式;
JSON独立于语言,具有自我描述性,更易理解;
JSON语法规则
- 数据由键(key)/值(value)描述,由逗号分隔
- 大括号代表一个完整的对象,拥有多个键/值对
- 中括号保存数组,多个对象之间使用逗号分隔
{
"site":[
{"name":"慕课网", "url":"www.imooc.com"},
{"name":"百度", "url":"www.baidu.com"},
{"name":"网易", "url":"www.163.com"}
]
}
JSON与字符串相互转换
- JSON.parse()方法将字符串转换为JSON对象
- JSON.stringify()方法将JSON对象转换为字符串
<!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>
JSON与Java交互
- Java的JSON工具包还有FastJson、Jackson、Gson、Json-lib...
- FastJson是阿里巴巴著名的JSON序列化与反序列工具包
- FastJson国内拥有大量使用者,拥有API简单,效率高等优点
FastJSON对象序列化与反序列化
Employee.java
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 + "]";
}
}
FastJsonSample.java
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);
}
}
控制台输出:
{"empName":"星海","hiredate":"2019-02-24"}
Employee [empId=0, empName=星海, empIn=Sun Feb 24 00:00:00 CST 2019]
FastJSON对象数组序列化与反序列化
-
JSON.toJSONString(list)
将对象数组序列化 -
JSON.parseArray(json, Employee.class)
将JSON数组反序列化
网友评论