當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang json.Marshal()用法及代碼示例

問題解決方法:

在這個程序中,我們將使用 json.Marshal() 函數對學生的結構進行編碼,然後在控製台屏幕上打印結果。

程序/源代碼:

下麵給出了使用 json.Marshal() 函數對結構進行編碼的源代碼。給定的程序在 ubuntu 18.04 操作係統上編譯和執行成功。

// Golang program to encode a structure
// using json.Marshal() function

package main

import "fmt"
import "encoding/json"

type Students struct {
	RollNo []int
	Names  []string
}

func main() {
	//Create an object of Students structure.
	stu:= &Students{
		RollNo:[]int{101, 102, 103},
		Names: []string{"Ravi", "Kavi", "Mavi"}}

	result, _:= json.Marshal(stu)
	fmt.Println(string(result))
}

輸出:

{"RollNo":[101,102,103],"Names":["Ravi","Kavi","Mavi"]}

說明:

在上麵的程序中,我們聲明了包 main。 main 包用於告訴 Go 語言編譯器必須編譯該包並生成可執行文件。在這裏,我們導入了 fmt、encoding/json 包,然後我們可以使用與 fmt 和 encoding/json 包相關的函數。

在 main() 函數中,我們使用 json.Marshal() 函數對學生的結構進行編碼。之後,我們在控製台屏幕上使用 string() 函數打印編碼值。





相關用法


注:本文由純淨天空篩選整理自 Golang program to encode a structure using json.Marshal() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。