MarshalJSON错误,顶级后面有无效字符”g”。

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年7月21日 17:50:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/31535710.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定