go json

go json转结构体怎么实现

小亿
108
2023-11-01 13:31:35
栏目: 编程语言

要将JSON转换为结构体,可以使用encoding/json包提供的Unmarshal函数。以下是一个简单的示例:

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结构体,并将其字段与JSON中的键对应起来。然后,我们使用json.Unmarshal函数将JSON数据解析到结构体变量中。最后,我们可以访问解析后的结构体的字段。

输出结果如下:

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

这样,我们就成功将JSON转换为结构体了。

0
看了该问题的人还看了