溫馨提示×

go json轉(zhuǎn)結(jié)構(gòu)體怎么實現(xiàn)

小億
123
2023-11-01 13:31:35
欄目: 編程語言

要將JSON轉(zhuǎn)換為結(jié)構(gòu)體,可以使用encoding/json包提供的Unmarshal函數(shù)。以下是一個簡單的示例:

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name    string   `json:"name"`
	Age     int      `json:"age"`
	Emails  []string `json:"emails"`
	Address struct {
		City    string `json:"city"`
		Country string `json:"country"`
	} `json:"address"`
}

func main() {
	jsonData := `{
		"name": "John Doe",
		"age": 30,
		"emails": ["john@example.com", "johndoe@example.com"],
		"address": {
			"city": "New York",
			"country": "USA"
		}
	}`

	var person Person
	err := json.Unmarshal([]byte(jsonData), &person)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Name:", person.Name)
	fmt.Println("Age:", person.Age)
	fmt.Println("Emails:", person.Emails)
	fmt.Println("Address:", person.Address)
}

在這個示例中,我們定義了一個Person結(jié)構(gòu)體,并將其字段與JSON中的鍵對應(yīng)起來。然后,我們使用json.Unmarshal函數(shù)將JSON數(shù)據(jù)解析到結(jié)構(gòu)體變量中。最后,我們可以訪問解析后的結(jié)構(gòu)體的字段。

輸出結(jié)果如下:

Name: John Doe
Age: 30
Emails: [john@example.com johndoe@example.com]
Address: {New York USA}

這樣,我們就成功將JSON轉(zhuǎn)換為結(jié)構(gòu)體了。

0