json就是JavaScript object Notation即js對象表示法,是一種輕量級數據交換格式。

json和對象互轉

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class Json {
    public static void main(String[] args) {
        //對象轉換爲json格式
        Student student = new Student("張三","男");
        String s = JSON.toJSONString(student);
        System.out.println(s);
        //列表轉換爲JSON
        List<Student> students = new ArrayList<>();
        students.add(student);
        students.add(new Student("李四","男"));
        String s1 = JSON.toJSONString(students);
        System.out.println(s1);

        //將JSON字符串轉換爲對象
        String jsonStr = "{\"name\":\"張三\",\"sex\":\"男\"}";
        Student student1 = JSON.parseObject(jsonStr, Student.class);
        System.out.println(student1);
    }
}

運行結果
在這裏插入圖片描述

	    Student student = new Student("張三","男");
  	    //給前端返回數據
        //一個空的json對象
        JSONObject jsonObject = new JSONObject();
        //添加數據
        jsonObject.put("status",200);
        jsonObject.put("data",student);
        //轉換爲json字符串
        String s2 = JSON.toJSONString(jsonObject);
        System.out.println(s2);

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章