To serialize and deserialize embedded structs in Go for data storage, you can use the encoding/json package. Here's an example:
type Address struct {
Street string
City string
Country string
}
type Person struct {
Name string
Age int
Address Address
}
import (
"encoding/json"
"fmt"
)
func main() {
person := Person{
Name: "John",
Age: 30,
Address: Address{
Street: "123 Main St",
City: "New York",
Country: "USA",
},
}
// Convert struct to JSON
jsonBytes, err := json.Marshal(person)
if err != nil {
fmt.Println("Error:", err)
return
}
jsonString := string(jsonBytes)
fmt.Println(jsonString)
}
func main() {
jsonString := `{"Name":"John","Age":30,"Address":{"Street":"123 Main St","City":"New York","Country":"USA"}}`
// Convert JSON to struct
var person Person
err := json.Unmarshal([]byte(jsonString), &person)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(person.Name)
fmt.Println(person.Age)
fmt.Println(person.Address.Street)
fmt.Println(person.Address.City)
fmt.Println(person.Address.Country)
}
Note that the tags in the struct fields can be used to customize the JSON field names and provide additional options for serialization and deserialization. For example:
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Country string `json:"country"`
}
This will serialize the Address
struct fields as street
, city
, and country
in the JSON output.