MarshalJSON 错误,顶级后无效字符 "g"
MarshalJSON error , invalid character "g" after top-level
我为我的 ID 创建了自定义类型:
type ID uint
func (id ID) MarshalJSON() ([]byte, error) {
e, _ := HashIDs.Encode([]int{int(id)})
fmt.Println(e) /// 34gj
return []byte(e), nil
}
func (id *ID) Scan(value interface{}) error {
*id = ID(value.(int64))
return nil
}
我使用 HashIDs 包对我的 ID 进行编码,这样用户就无法在客户端读取它们。但我收到此错误:
json: error calling MarshalJSON for type types.ID: invalid character 'g' after top-level value
34gj
不是有效的 JSON,因此不是您 ID 的有效字符串表示形式。您可能想用双引号将其括起来以指示这是一个字符串,即 returning "34gj"
.
尝试:
func (id ID) MarshalJSON() ([]byte, error) {
e, _ := HashIDs.Encode([]int{int(id)})
fmt.Println(e) /// 34gj
return []byte(`"` + e + `"`), nil
}
http://play.golang.org/p/0ESimzPbAx
除了手动操作,您还可以为字符串调用 marshaller,只需将 return 替换为 return json.Marshal(e)
。
我猜你的错误中 invalid character 'g'
是由于值的初始部分被视为数字,然后出现意外字符。
我为我的 ID 创建了自定义类型:
type ID uint
func (id ID) MarshalJSON() ([]byte, error) {
e, _ := HashIDs.Encode([]int{int(id)})
fmt.Println(e) /// 34gj
return []byte(e), nil
}
func (id *ID) Scan(value interface{}) error {
*id = ID(value.(int64))
return nil
}
我使用 HashIDs 包对我的 ID 进行编码,这样用户就无法在客户端读取它们。但我收到此错误:
json: error calling MarshalJSON for type types.ID: invalid character 'g' after top-level value
34gj
不是有效的 JSON,因此不是您 ID 的有效字符串表示形式。您可能想用双引号将其括起来以指示这是一个字符串,即 returning "34gj"
.
尝试:
func (id ID) MarshalJSON() ([]byte, error) {
e, _ := HashIDs.Encode([]int{int(id)})
fmt.Println(e) /// 34gj
return []byte(`"` + e + `"`), nil
}
http://play.golang.org/p/0ESimzPbAx
除了手动操作,您还可以为字符串调用 marshaller,只需将 return 替换为 return json.Marshal(e)
。
我猜你的错误中 invalid character 'g'
是由于值的初始部分被视为数字,然后出现意外字符。