英文:
How to send a nested map from server to client using jsonrpc package in golang?
问题
我正在编写一个客户端服务器的Go应用程序,它使用Yahoo Finance API获取实时股票价格。我正在使用jsonrpc包连接客户端和服务器。
我无法将服务器端的嵌套映射响应传递给客户端。这是客户端文件的一个小片段。client.go文件:
var (
reply map[string]map[int]float64
)
c := jsonrpc.NewClient(client)
err = c.Call("JSONResponse.GetStockValue", args, &reply)
fmt.Println(reply)
服务器文件如下:
func (j *JSONResponse) GetStockValue(args *ClientRequest, reply *map[string]map[int]float64) error {
// 一些代码...
nestedMap := make(map[string]map[int]float64)
// 在嵌套映射中添加一些值...
fmt.Println(nestedMap)
*reply = nestedMap
return nil
}
这不会向客户端发送任何响应。当我将嵌套映射更改为简单的映射,如map[string]int
时,它可以正常工作。嵌套映射在服务器端正确显示,但在客户端端不显示。客户端只是一直等待服务器的响应。如果有人能指导我为什么它不接受嵌套映射并且对简单映射正常工作,那将非常有帮助。谢谢
英文:
I am writing a client server go application which uses yahoo finance api to fetch the real time stock price. I am using jsonrpc package to connect client and server.
I am unable to pass a nested map response from server to client. Here is my small snippet from the client file. client.go file
var (
reply map[string]map[int]float64
)
c := jsonrpc.NewClient(client)
err = c.Call("JSONResponse.GetStockValue", args, &reply)
fmt.Println(reply)
Server file looks like this:
func (j *JSONResponse) GetStockValue(args *ClientRequest, reply *map[string]map[int]float64) error {
some piece of code......
nestedMap := make(map[string]map[int]float64)
add some values in nested map .....
fmt.Println(nestedMap)
*reply = nestedMap
return nil
}
This does not send any response to the client. When i change the nested map to simple map like map[string]int, it correctly works. The nested map is correctly displayed at server but does not get displayed on the client side. The client simply keeps on waiting for the response from the server. It would be very helpful if someone could guide me on why it is not accepting a nested map and working fine for a simple map ?
Thanks
答案1
得分: 1
jsonrpc
是 json rpc
,因为它使用 json
进行序列化。要将一个 map 编组为 json
,你需要使用 string
类型的键。请参考 encoding/json。
英文:
jsonrpc
is json rpc
because it use json
for serialization. to Marshal a map to json
, you need string
key type. refer to encoding/json
答案2
得分: 0
如果你在这里打印出你的err
,err = c.Call("JSONResponse.GetStockValue", args, &reply)
,你应该会看到错误原因是invalid character '' looking for beginning of object key string.
JSON规范指出对象的键必须是string
类型。
或者如果你的JSON使用了string
类型,那么错误信息是json: cannot unmarshal object into Go value of type map[int]float64
。
英文:
If you print out your err
here err = c.Call("JSONResponse.GetStockValue", args, &reply)
you should see the reason invalid character '' looking for beginning of object key string.
The JSON spec says the object's key needs to be string
.
Or if you JSON is using string
, then json: cannot unmarshal object into Go value of type map[int]float64
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论