How does Go handle data serialization and deserialization?
In Go, data serialization and deserialization can be achieved using the encoding/json package, which provides functionality for converting Go data structures to JSON and vice versa. The package also supports other data formats such as XML and Protocol Buffers.
To serialize a Go data structure to JSON, you can use the json.Marshal() function, which takes the data structure as an input and returns a byte slice containing the JSON representation of the data. For example:
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
person := Person{Name: "John Doe", Age: 30}
jsonBytes, err := json.Marshal(person)
if err != nil {
fmt.Println(err)
}
jsonString := string(jsonBytes)
fmt.Println(jsonString)
}
This will output:
{"name":"John Doe","age":30}
To deserialize a JSON string to a Go data structure, you can use the json.Unmarshal() function, which takes the JSON byte slice as input and a pointer to the target data structure. For example:
func main() {
jsonString := `{"name":"John Doe","age":30}`
var person Person
err := json.Unmarshal([]byte(jsonString), &person)
if err != nil {
fmt.Println(err)
}
fmt.Println(person.Name)
fmt.Println(person.Age)
}
This will output:
John Doe
30
In addition to the encoding/json package, Go also has support for other data serialization formats such as encoding/xml and the popular Protocol Buffers through the use of third-party libraries.