1. 程式人生 > >Go語言基礎(十五)—— Go語言實現json資料檔案讀取與儲存

Go語言基礎(十五)—— Go語言實現json資料檔案讀取與儲存

案例:

package main

import (
	"os"
	"fmt"
	"encoding/json"
	"time"
)

type Person2 struct {
	Name string
	Age int
	Sex string
	Hobby []string
}

func main() {
	//初始化結構體
	wek := Person2{"wek",18,"男",[]string{"女","study","play"}}
	var wek2 Person2

	//建立或者開啟檔案
	file, e := os.Create("./temp.txt")
	if e!=nil{
		fmt.Println("建立檔案失敗!",e)
	}
	//生成檔案編碼器
	encoder:= json.NewEncoder(file)
	//使用編碼器將結構體編碼到檔案中
	encode := encoder.Encode(wek)
	if encode!=nil{
		fmt.Println("wek寫入檔案失敗!")
	}
	file.Close()
	//睡兩秒
	time.Sleep(2*time.Second)
	//開啟檔案
	open, i := os.Open("./temp.txt")
	if i!=nil{
		fmt.Println("檔案開啟失敗!")
	}
	//程式碼執行最後將檔案關閉
	defer open.Close()

	//生成檔案解碼器
	decoder := json.NewDecoder(open)
	decode := decoder.Decode(&wek2)
	if decode!=nil{
		fmt.Println("檔案反序列化失敗!")
	}
	fmt.Println(wek2)
}

結果為: