JSON
1.1 JSON格式概述
JSON
JavaScript
JavaScript Object Notation
(JavaScript Object Notation,JavaScript對象表示法,讀作/ˈdʒeɪsən/)是一種輕量級的數據交換語言,該語言以易於讓人閱讀的文字爲基礎,用來傳輸由屬性值或者序列性的值組成的數據對象。儘管JSON是JavaScript的一個子集,但JSON是獨立於語言的文本格式,並且採用了類似於C語言家族的一些習慣
{
"firstName": "John",
"lastName": "Smith",
"sex": "male",
"age": 25,
"married": false,
"address":
{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber":
[
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
1.2 數據格式
1.2.1 JSON對象
{
"ID":001,
"name":"騷磊",
"age":16
}
特徵:
1. 數據形式鍵值對形式
"鍵":值
2. 數據支持 字符串,數字,true false
3. {} 大括號以內的數據
1.2.2 JSON對象數組
[
{
"ID":1,
"name":"騷磊",
"age":16
},
{
"ID":2,
"name":"騷傑",
"age":66
},
{
"ID":3,
"name":"康康",
"age":15
}
]
特徵:
1. 數據使用[]包含
2. 在[]都是JSON格式對象
3. 每一個對象之間使用逗號隔開,同時最後一個元素不需要逗號
1.2.3 JSON數據驗證
JSON格式驗證
1.3 解析JSON格式工具
常用的工具:
Gson,fastjson, Jackson
以上都是第三方工具,需要導入對應的jar包按使用
XML導包
1.3.1 FastJson內容
JSON核心類
JSON核心類提供解析和轉化方法,用於解析JSON數據格式,同時用於轉換類對象到JSON格式,該類對象需要符合JavaBean規範
--| JSONArray
存在按照鍵值對方式解析獲取數據,同時存在一定的List方法
--| JSONObject
獲取對應的類對象,指定鍵值對對應數據的方法
1.3.2 解析演示
public class Student {
private Strint name;
private Integer age;
}
package com.qfedu.b_json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.ir.CallNode;
import java.util.ArrayList;
import java.util.List;
public class Demo1 {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
Student stu = new Student("騷磊", 16);
list.add(stu);
list.add(new Student("騷傑", 66));
list.add(new Student("老黑", 56));
list.add(new Student("老付", 36));
list.add(new Student("老高", 66));
String s = JSON.toJSONString(list);
System.out.println(s);
System.out.println("--------------------------------------");
String s1 = JSON.toJSONString(stu);
System.out.println(s1);
Student student = JSON.parseObject(s1, Student.class);
System.out.println(student);
JSONObject jsonObject = JSON.parseObject(s1);
String name = jsonObject.getString("name");
System.out.println(name);
System.out.println(jsonObject.getInteger("age"));
JSONArray objects = JSON.parseArray(s);
System.out.println(objects);
for (Object object : objects) {
JSONObject jsonObject1 = (JSONObject) object;
System.out.println(jsonObject1.getString("name"));
System.out.println(jsonObject1.getInteger("age"));
}
Student object = objects.getObject(2, Student.class);
System.out.println(object);
System.out.println("--------------------------------------");
List<Student> students = objects.toJavaList(Student.class);
for (Student student1 : students) {
System.out.println(student1);
}
System.out.println("--------------------------------------");
}
}