使用`json:",字符串"返回无效使用字符串结构标签,尝试解除未引用的值 [英] Using `json:",string"` returning invalid use of ,string struct tag, trying to unmarshal unquoted value

查看:861
本文介绍了使用`json:",字符串"返回无效使用字符串结构标签,尝试解除未引用的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图解析一个带有float值的json时,距离下面的struct

 类型CreateBookingRequest struct {
距离float64`json:distance,string`
DistanceSource string`json:distanceSource`
}

我得到以下错误:


json:无效使用,string结构标记,尝试解组未引用
值转换为[34 100 105 115 116 97 110 99 101 34]%!(EXTRA
* reflect.rtype = dto.CreateBookingRequest)

有没有办法让我避免错误/得到更好的错误信息?

编辑:
我实际上期望API的用户传入一个字符串值,但如果他们出于某种原因在非字符串值中,我希望能够清楚地告诉他们,而不是难以阅读的错误消息。

解决方案

我不得不使用有时引用数字并且有时不引用数字的API。该服务的所有者不可能解决它,所以我想出了一个简单的解决方法:

  re:= regexp .MustCompile(`:\s *)([\d\。] +)(\s * [,}])`)
rawJsonByteArray = re.ReplaceAll(rawJsonByteArray,[] byte ('$ 1'$ 2$ 3`))

正则表达式效率有点低,但我没有相信我能够实现更快的实现。

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.

解决方案

I had to work with an API which sometimes quotes numbers and sometimes doesn't. The owners of the service weren't likely to fix it, so I came up with a simple workaround:

re := regexp.MustCompile(`(":\s*)([\d\.]+)(\s*[,}])`)
rawJsonByteArray = re.ReplaceAll(rawJsonByteArray, []byte(`$1"$2"$3`))

Regular expressions are somewhat inefficient, but I don't believe I'd be able to implement something substantially faster.

这篇关于使用`json:",字符串"返回无效使用字符串结构标签,尝试解除未引用的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆