有这样的结构:
Programs struct {
ID int `json:"id"`
ShortName string `json:"short_name"`
ProgramPoints float64 `json:"program_points"`
Countries []string `json:"countries"`
}列countries是包含国家["US","GB"]解析数组的JSON列:
stmt, err := db.Query(sql)
err = stmt.Scan(
&program.ID,
&program.ShortName,
&program.ProgramPoints,
&program.Countries)有错误的unsupported Scan, storing driver.Value type []uint8 into type *[]字符串,我找到了如何将JSON解析为struct,而不是数组。提前为您提供任何帮助
发布于 2022-07-21 09:46:14
因此,当您希望JSON值来自DB和be (Un)自动封送时,您需要为此创建一个类型:
type Programs struct {
ID int `json:"id"`
ShortName string `json:"short_name"`
ProgramPoints float64 `json:"program_points"`
Countries Countries `json:"countries"`
}
type Countries []string
func (c Countries) Value() (driver.Value, error) {
return json.Marshal(c) // return json marshalled value
}
func (c *Countries) Scan(v interface{}) error {
switch tv := v.(type) {
case []byte:
return json.Unmarshal(tv, &c) // unmarshal
case []uint8:
return json.Unmarshal([]byte(tv), &c) // can't remember the specifics, but this may be needed
}
return errors.New("unsupported type")
}应该能处理stmt.Scan的东西
https://stackoverflow.com/questions/73063654
复制相似问题