Go does not have a built-in code generator to convert between JSON and structs; you must use the encoding/json package to marshal and unmarshal data manually. Define your struct with JSON tags to map fields, then use json.Unmarshal to convert JSON bytes to the struct and json.Marshal to convert the struct back to JSON bytes.
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
jsonStr := `{"name":"Alice","age":30}`
var u User
if err := json.Unmarshal([]byte(jsonStr), &u); err != nil {
panic(err)
}
fmt.Println(u.Name) // Output: Alice
out, _ := json.Marshal(u)
fmt.Println(string(out)) // Output: {"name":"Alice","age":30}
}