JSON
JavaScriptのオブジェクト表記法(JavaScriptのオブジェクト表記)。
JSONは軽量のテキストデータ交換フォーマットです。
JSONの言語に依存しない、自己記述、理解しやすいです。
JSONの構文規則
- 鍵(キー)/値(値)によって記述されたデータは、カンマで区切っ
- 完全なオブジェクトは、代表者をブレース複数のキー/値のペアを持っています
- ブラケットバックアップ配列、カンマで区切られた複数のオブジェクト
{
"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、ジャクソン、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配列のデシリアライズ