go json转结构体怎么实现

   2025-02-15 6190
核心提示:要将JSON转换为结构体,可以使用encoding/json包提供的Unmarshal函数。以下是一个简单的示例:package mainimport (encoding/jso

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

package mainimport ("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 Personerr := 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 DoeAge: 30Emails: [john@example.com johndoe@example.com]Address: {New York USA}

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言