Types golang中的json rpc,id为字符串
我是新来的 我使用这个包来执行json rpc v 1.0请求(因为golang只实现2.0) 我有一个问题,我调用的这个服务器将“id”作为字符串返回,如Types golang中的json rpc,id为字符串,types,go,json-rpc,Types,Go,Json Rpc,我是新来的 我使用这个包来执行json rpc v 1.0请求(因为golang只实现2.0) 我有一个问题,我调用的这个服务器将“id”作为字符串返回,如 "id":"345" 而不是 "id":345 我找到的唯一方法是使用字符串而不是uint64重新定义clientResponse type clientResponse struct { Result *json.RawMessage `json:"result"` Error interface{} `j
"id":"345"
而不是
"id":345
我找到的唯一方法是使用字符串而不是uint64重新定义clientResponse
type clientResponse struct {
Result *json.RawMessage `json:"result"`
Error interface{} `json:"error"`
Id string `json:"id"`
}
重新定义完全相同的DecodeClientResponse函数来使用我的clientResponse
我调用(DecodeClientResponse而不是gjson.DecodeClientResponse)而不是CallJson:
我觉得这很难看,有没有更好的办法
谢谢试试看
type clientResponse struct {
Result *json.RawMessage `json:"result"`
Error interface{} `json:"error"`
# Tell encoding/json that the field is
# encoded as a json string even though the type is int.
Id int `json:"id,string"`
}
只要库在引擎盖下使用编码/json,这应该可以工作。json rpc v 1.0规定: id-请求id。它可以是任何类型。它用于将响应与其响应的请求相匹配 也就是说,
id
可以是任何东西(甚至是一个数组),服务器响应应该包含相同的id值和类型,而在您的情况下它不会这样做。因此,与您通信的服务器没有正确执行其工作,并且没有遵循json rpc v 1.0规范
所以,是的,你需要做“丑陋”的解决方案,并为这个“坏”的服务器创建一个新的解码器功能。Jeremy Wall的建议有效(但是int
应该改为uint64
),至少应该避免使用字符串作为类型
编辑
我对httprpc
包的了解还不足以了解它如何处理Id
值。但如果您想要字符串或int,您应该能够将clientResponse
中的Id设置为:
Id interface{} `json:"id"`
检查Id
中的值时,使用类型开关:
var id int
// response is of type clientResponse
switch t := response.Id.(type) {
default:
// Error. Bad type
case string:
var err error
id, err = strconv.Atoi(t)
if err != nil {
// Error. Not possible to convert string to int
}
case int:
id = t
}
// id now contains your value
谢谢,可以同时解码int和string,比如如果int不起作用,试试string。或者我应该这样做:StringId stringjson:“id”
和IntId uint64json:“id”
?是的,这是可能的。我对httprpc
包的了解还不足以了解它如何处理id
值。但是我编辑了答案来展示如何使用接口{}
而不是字符串。
var id int
// response is of type clientResponse
switch t := response.Id.(type) {
default:
// Error. Bad type
case string:
var err error
id, err = strconv.Atoi(t)
if err != nil {
// Error. Not possible to convert string to int
}
case int:
id = t
}
// id now contains your value