英文:
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: 调用类型types.ID的MarshalJSON时出错:顶级值后面有无效字符'g'
英文:
I made a custom type for my IDs:
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
}
I use the HashIDs package to encode my ids so that user wont be able to read them on client side. But I'm getting this error:
> json: error calling MarshalJSON for type types.ID: invalid character 'g' after top-level value
答案1
得分: 13
34gj 不是有效的 JSON,因此也不是您的 ID 的有效字符串表示。您可能希望用双引号将其包裹起来,以表示这是一个字符串,即返回 "34gj"。
尝试以下代码:
func (id ID) MarshalJSON() ([]byte, error) {
    e, _ := HashIDs.Encode([]int{int(id)})
    fmt.Println(e) /// 34gj
    return []byte(`"` + e + `"`), nil
}
您也可以通过调用字符串的编组器来完成,只需将返回语句替换为 return json.Marshal(e)。
我猜测您的错误信息中的 invalid character 'g' 是由于值的初始部分被视为数字,然后出现了意外的字符。
英文:
34gj is not a valid JSON and hence not a valid string representation of your ID. You probably want to wrap this with double quotation mark to indicate this is a string, i.e. returning "34gj".
Try:
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
Instead of doing it by hand you can also call marshaller for the string, by simply replacing your return with return json.Marshal(e).
My guess would be that invalid character 'g' in your error is due to initial part of the value is being treated as a number and then unexpected character occurs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论