1. 程式人生 > 其它 >JSON資料處理

JSON資料處理

JSON資料處理

JSON資料處理

1.json的資料格式

1.1 陣列格式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
      /*
      * 定義json的格式陣列格式
      * 中括號包裹,陣列的元素的資料型別沒有限制
      * 元素之間,逗號分開
      * */

      var jsonArray = ["k1","k2",100,9.9,true];
      //訪問資料元素,通過索引訪問
      console.log(jsonArray[1]);
      //遍歷陣列,取出陣列中的元素
      for(var i=0;i<jsonArray.length; i++){
        console.log(jsonArray[i]);
      }

    </script>
</head>
<body>

</body>
</html>

1.2 物件格式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
      /*
      * 定義json的物件格式
      * 大括號包裹,定義鍵值對,鍵必須是字串型別,值得資料型別不限制
      * 鍵值對之間,是冒號分開
      * 每個鍵值對之間,逗號分開
      * */

      var jsonObject={
        "k1":"v1",
        "k2":"v2",
        "k3":100,
        "k4":9.9,
        "k5":true
      }
      //取出鍵值對,鍵找值的方式
      console.log(jsonObject.k1);
      console.log(jsonObject.k2);
      console.log(jsonObject.k3);
      console.log(jsonObject.k4);
      console.log(jsonObject.k5);

    </script>
</head>
<body>

</body>
</html>

1.3 資料巢狀物件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>json資料的巢狀</title>
  <script type="text/javascript">
    /*
    * json資料的元素是物件
    * */

    var jsonArray = [
      {"name":"張三","age":20},
      {"name":"李四","age":22}
    ]

    //取出需要的資料 ,李四 22
    console.log( jsonArray[1].name+"----"+jsonArray[1].age);
    //遍歷資料,取出陣列中的元素
    for (var i = 0; i < jsonArray.length; i++) {
      console.log(jsonArray[i].name +"----"+jsonArray[i].age);
    }

  </script>
</head>
<body>

</body>
</html>

1.4 物件巢狀資料

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        /*
        * json資料是物件,物件值是陣列
        * */

        var jsonObject = {
            "k1": ["北京","上海","廣州","深圳"],
            "k2": ["中國","美國","英國","法國"]
        }
        //取出上海
        console.log(jsonObject.k1[1]);
        //分別取出k1和k2鍵的陣列,遍歷
        for (var i = 0; i < jsonObject.k1.length; i++) {
            console.log(jsonObject.k1[i]);
        }
        console.log("============================================")
        for (var i = 0; i < jsonObject.k2.length; i++) {
            console.log(jsonObject.k2[i]);
        }
    </script>
</head>
<body>

</body>
</html>

1.5 json巢狀

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>json資料的巢狀</title>
    <script type="text/javascript">
      /*
      *  json的資料巢狀,你中有我,我中有你
      *  json的資料本質是物件
      *    物件是的鍵是字串,物件的值是陣列
      *    陣列的元素是物件
      * */

      var json = {
        //鍵是k1,值是陣列,陣列的元素是物件
        "k1":[
          //陣列的元素是兩個物件
          {"name":"張三","age":20},
          {"name":"李四","age":21},
        ],
        "k2":[
          //陣列的元素是兩個物件
          {"name":"王五","age":23},
          {"name":"趙六","age":24},
        ],
      }

      //取出資料 李四 21
      console.log(json.k1[1].name+"---"+json.k1[1].age);

      //遍歷k2鍵對應的陣列
      for (var i = 0; i <json.k2.length ; i++) {
          console.log(json.k2[i].name+"---"+json.k2[i].age);
      }
    </script>
</head>
<body>

</body>
</html>

2.fastjson

它可以解析JSON格式的字串,支援將Java Bean序列化為JSON字串,也可以從JSON字串反序列化到Java Bean。

@Data
public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private String email;
    private Date birthday;
}

2.1 Java物件序列化到Json

//java中的物件,Student物件,序列化Json格式字串
    @Test
    public void testObjectToJson(){
        Student student = new Student();
        student.setId(1);
        student.setName("張三");
        student.setAge(20);
        student.setEmail("[email protected]");
        student.setBirthday(getDate());
        //student物件轉成json格式的字串
        //呼叫靜態方法,傳遞要抓換的物件
        String jsonString = JSON.toJSONString(student);
        System.out.println(jsonString);
        //{"age":20,"birthday":1629451099346,"email":"[email protected]","id":1,"name":"張三"}
    }
{
    "age":20,
    "birthday":1629451099346,
    "email":"[email protected]",
    "id":1,
    "name":"張三"
}
//java中的集合List,序列化為Json格式字串
    @Test
    public void testListToJson(){
        //集合List,儲存Student物件
        ArrayList<Student> list = new ArrayList<>();
        Student student1 = new Student();
        student1.setId(1);
        student1.setName("張三");
        student1.setAge(20);
        student1.setEmail("[email protected]");
        student1.setBirthday(getDate());

        Student student2 = new Student();
        student2.setId(2);
        student2.setName("趙四");
        student2.setAge(25);
        student2.setEmail("[email protected]");
        student2.setBirthday(getDate());
        //student物件儲存到集合中
        list.add(student1);
        list.add(student2);
        //List集合,序列化為Json格式字串
        String jsonString = JSON.toJSONString(list);
        System.out.println(jsonString);
        //轉後的結果是陣列,陣列的元素是物件
        //[{"age":20,"birthday":1629451016542,"email":"[email protected]","id":1,"name":"張三"},
        // {"age":25,"birthday":1629451016542,"email":"[email protected]","id":2,"name":"趙四"}]

    }
[
    {"age":20,"birthday":1629451016542,"email":"[email protected]","id":1,"name":"張三"},
    {"age":25,"birthday":1629451016542,"email":"[email protected]","id":2,"name":"趙四"}
]
    //java中的集合Map,序列化為Json格式字串
    @Test
    public void testMapToJson(){
        //建立map集合,鍵為字串型別,值為Student物件
        HashMap<String, Student> map = new HashMap<>();

        Student student1 = new Student();
        student1.setId(1);
        student1.setName("張三");
        student1.setAge(20);
        student1.setEmail("[email protected]");
        student1.setBirthday(getDate());

        Student student2 = new Student();
        student2.setId(2);
        student2.setName("趙四");
        student2.setAge(25);
        student2.setEmail("[email protected]");
        student2.setBirthday(getDate());
        //Map集合儲存Student物件
        map.put("student1",student1);
        map.put("student2",student2);

        String jsonString = JSON.toJSONString(map);
        System.out.println(jsonString);
        //json格式字串是物件,物件中有兩個鍵,鍵對應的值是Student物件
        //{"student2":{"age":25,"birthday":1629451782886,"email":"[email protected]","id":2,"name":"趙四"},
        // "student1":{"age":20,"birthday":1629451782886,"email":"[email protected]","id":1,"name":"張三"}}

    }
{
    "student2":{"age":25,"birthday":1629451782886,"email":"[email protected]","id":2,"name":"趙四"},
    "student1":{"age":20,"birthday":1629451782886,"email":"[email protected]","id":1,"name":"張三"}
}

2.2 Json反序列化到java物件

 //Json格式字串,反序列化到Java物件
    @Test
    public void testJsonToObject(){
        String jsonString = "{\"age\":20,\"birthday\":1629451099346,\"email\":\"[email protected]\",\"id\":1,\"name\":\"張三\"}";
        //Json類的靜態方法  parseObject
        //傳遞要反序列化的Json字串,傳遞Java物件的class物件
        Student student=JSON.parseObject(jsonString,Student.class);
        System.out.println(student);
    }
 //Json格式字串,反序列化到List集合
    @Test
    public void testJsonToList(){
        String jsonString = "[{\"age\":20,\"birthday\":1629451016542,\"email\":\"[email protected]\",\"id\":1,\"name\":\"張三\"},\n" +
                " {\"age\":25,\"birthday\":1629451016542,\"email\":\"[email protected]\",\"id\":2,\"name\":\"趙四\"}]";
        //Json類的靜態方法  parseArray
        //傳遞Json格式的字串,傳遞轉換後的集合的泛型的class物件
        List<Student> list = JSON.parseArray(jsonString, Student.class);
        list.forEach(System.out::println);
    }
//Json格式字串,反序列化到Map集合
    @Test
     public void testJsonToMap(){
        String jsonString = "{\"student2\":{\"age\":25,\"birthday\":1629455067665,\"email\":\"[email protected]\",\"id\":2,\"name\":\"趙四\"}," +
                "\"student1\":{\"age\":20,\"birthday\":1629455067665,\"email\":\"[email protected]\",\"id\":1,\"name\":\"張三\"}}";
        //json類的靜態方法,parseObject
        //直接進行反序列化,Map集合是沒有泛型的,泛型沒有事不安全的
        //轉後的集合,必須有泛型
        //呼叫parseObject,傳遞引數,TypeReference型別
        //將Map中所有的鍵存入到set集合中。因為set具備迭代器。所有可以迭代方式取出所有的鍵,再根據get方法。獲取每一個鍵對應的值。
        //keySet():迭代後只能通過get()取key
        Map<String, Student> map = JSON.parseObject(jsonString, new TypeReference<Map<String, Student>>() {});
        for (String key : map.keySet()){
            System.out.println(key+":"+map.get(key));
        }
    }