type User struct { Name string Age int } func ToJSON(user User) []byte { v := reflect.ValueOf(user) if v.Kind() != reflect.Struct { panic("ToJSON only accepts structs") } b, err := json.Marshal(user) if err != nil { panic(err) } return b }
func FromJSON(data []byte, ptr interface{}) error { v := reflect.ValueOf(ptr) if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { return errors.New("FromJSON accepts only pointers to structs") } return json.Unmarshal(data, ptr) }In this example, we use the reflect package to ensure that the passed parameter is a pointer to a struct. We then use the json.Unmarshal function to deserialize the JSON byte slice into the struct. The package library used in these examples is the standard library reflect and encoding/json.