Home > Article > Backend Development > How to use reflection for serialization and deserialization in golang
Serialization and deserialization using Go reflection: Serialization: Use the encoding/json.Marshal function to serialize the structure to a byte stream. Deserialization: Use the encoding/json.Unmarshal function to deserialize a structure from a byte stream.
Reflection is a powerful feature in Go that allows you to inspect and modify a running program. It can be used for a variety of purposes, including serialization and deserialization, and it allows you to save data structures as byte streams and then recreate them later.
To use reflection to serialize a structure, use the Marshal
function in the encoding/json
package. This function requires a pointer to a structure as its first argument and returns a serialized slice of bytes.
package main import ( "encoding/json" "fmt" "io/ioutil" "os" ) type person struct { FirstName string LastName string Age int } func main() { p := person{FirstName: "John", LastName: "Doe", Age: 30} b, err := json.Marshal(&p) if err != nil { panic(err) } // 保存序列化后的数据到文件 err = ioutil.WriteFile("person.json", b, 0644) if err != nil { panic(err) } }
To deserialize serialized data, use the Unmarshal
function in the encoding/json
package. The function requires a pointer to a structure as its first argument, and a slice of bytes containing the serialized data as its second argument.
func main() { var p person b, err := ioutil.ReadFile("person.json") if err != nil { panic(err) } // 反序列化数据到结构 err = json.Unmarshal(b, &p) if err != nil { panic(err) } // 打印反序列化的数据 fmt.Printf("%+v\n", p) }
The following is a practical example of using reflection for serialization and deserialization:
type user struct { ID int Name string } var users = []user{ {1, "john"}, {2, "jane"}, } var b []byte func main() { // 序列化用户数组 b, _ = json.Marshal(users) // 将序列化后的数据保存到文件中 ioutil.WriteFile("users.json", b, 0644) // 反序列化文件中的数据 var loadedUsers []user json.Unmarshal(b, &loadedUsers) // 打印反序列化的用户 fmt.Println(loadedUsers) }
The above is the detailed content of How to use reflection for serialization and deserialization in golang. For more information, please follow other related articles on the PHP Chinese website!