douchan0523 2015-07-21 09:50
浏览 308
已采纳

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条回答 默认 最新

  • 普通网友 2015-07-21 10:17
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示