Go 将复杂结构体struct转换为字符串string的简单例子

以下是一个将复杂结构体转化为字符串的简单例子

package main

import (
	"encoding/json"
	"fmt"
)

type student struct {
	name string
	age  int
}

type grade struct {
	id       int
	students []student
}

func main() {
	//以下是定义几个变量
	allstudent := []grade{}
	grade1 := grade{id: 1}
	grade2 := grade{id: 2}
	student1 := student{name: "yiyi", age: 6}
	student2 := student{name: "yier", age: 7}
	student3 := student{name: "eryi", age: 8}
	//以下是填充结构体
	grade1.students = append(grade1.students, student1)
	grade1.students = append(grade1.students, student2)
	grade2.students = append(grade2.students, student3)
	allstudent = append(allstudent, grade1)
	allstudent = append(allstudent, grade2)

	//以下是将结构体转化为string
	allstudentjson, _ := json.Marshal(allstudent)
	fmt.Println(string(allstudentjson))
}

以上代码直接运行会输出 [{},{}],说明转化没有达到预期。
添加以下两个函数,针对student与grade结构体,重载MarshalJson函数(这个是成功达到预期的关键)。

func (stu student) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{
		"name": stu.name,
		"age":  stu.age,
	})
}

func (grade grade) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{
		"id":       grade.id,
		"students": grade.students,
	})
}

再次运行,输出结果为[{“id”:1,“students”:[{“age”:6,“name”:“yiyi”},{“age”:7,“name”:“yier”}]},{“id”:2,“students”:[{“age”:8,“name”:“eryi”}]}]

你可能感兴趣的:(go)