dreamer1231 2015-03-23 15:21
浏览 1518

使用`json:“,string“`返回无效使用,string struct标签,试图解组未引用的值

When trying to parse a json with a float value for distance to the following struct

type CreateBookingRequest struct {
    Distance          float64           `json:"distance,string"`
    DistanceSource    string            `json:"distanceSource"`
}

I get the following error

json: invalid use of ,string struct tag, trying to unmarshal unquoted value into [34 100 105 115 116 97 110 99 101 34]%!(EXTRA *reflect.rtype=dto.CreateBookingRequest)

Is there a way for me to avoid the error/get a better error message?

Edit: I am actually expecting the users of the API to pass in a string value but if they for some reason pass in a non-string value, I would like to be able to tell them clearly, instead of this hard to read error message.

  • 写回答

4条回答 默认 最新

  • dprfe04886 2015-03-23 15:51
    关注

    This error happens when the "distance" JSON value is encoded as a number instead of a string (per the "string" tag on the "Distance") field:

    str := []byte(`{"distance":1.23,"distanceSource":"foo"}`)
    // Note JSON number -------^
    var cbr CreateBookingRequest
    err := json.Unmarshal(str, &cbr)
    // err => json: invalid use of ,string struct tag, trying to unmarshal unquoted value into [34 100 105 115 116 97 110 99 101 34]%!(EXTRA *reflect.rtype=main.CreateBookingRequest)
    

    If you change the type of the distance value to a string (per the tag) then it works fine:

    str := []byte(`{"distance":"1.23","distanceSource":"foo"}`)
    // Note JSON string -------^
    

    You could change the error message by identifying that specific error somehow and provide a different message. You might also consider changing the tag for the Distance type to simply accept a number instead of a string:

    type CreateBookingRequest struct {
      Distance       float64 `json:"distance"`
      ...
    }
    
    ...
      str := []byte(`{"distance":1.23,"distanceSource":"foo"}`)
    
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮