英文:
Encode Set data structure in Golang
问题
我在Go中使用Set数据结构实现了基本操作,如Add、Remove、Difference和Union。我试图使用json编码器发送一个HTTP请求,以编码请求体,其中包含形式为map[string]Set
的对象。Set数据结构的定义如下:
type Set map[interface{}]struct{}
func NewSet() Set {
set := make(Set)
return set
}
编码器的代码如下:
func (req *Request) BodyContentInJson(val interface{}) error {
buf := bytes.NewBuffer(nil)
enc := json.NewEncoder(buf)
if err := enc.Encode(val); err != nil {
return err
}
req.Obj = val
req.Body = buf
req.BodySize = int64(buf.Len())
return nil
}
这段代码在以下位置失败:
if err := enc.Encode(val); err != nil {
return err
}
并给出错误信息:{"errors":["json: unsupported type: Set"]}
。当我调试时,val
的类型是map[string]interface{}
。
在这里,我应该如何编码和解码JSON内容,使用Go的编码器?
英文:
I have a Set data structure implemented in Go with the basic operations like Add, Remove, Difference, Union. I am trying to send a http request using the json encoder to encode the request body which contains the object of the form map[string]Set
. The Set data structure is defined below:
type Set map[interface{}]struct{}
func NewSet() Set {
set := make(Set)
return set
}
The encoder looks like this:
func (req *Request) BodyContentInJson (val interface{}) error {
buf := bytes.NewBuffer(nil)
enc := json.NewEncoder(buf)
if err := enc.Encode(val); err != nil {
return err
}
req.Obj = val
req.Body = buf
req.BodySize = int64(buf.Len())
return nil
}
This code fails at
if err := enc.Encode(val); err != nil {
return err
}
giving an error:{"errors":["json: unsupported type: Set"]}
. Also, the type of val
is map[string]interface{}
when I debugged it.
How could I possibly encode and marshal/unmarshal JSON content here using the Go's encoder ?
答案1
得分: 1
你可以在*Set
类型上编写自己的UnmarshalJSON
方法,然后json.Encoder
将使用该方法将JSON数据编码到Set
中。这里有一个简单的示例:https://play.golang.org/p/kx1E-jDu5e。
顺便说一下,你之所以会收到错误是因为interface{}
类型的映射键不受encoding/json
包支持。 (https://github.com/golang/go/blob/master/src/encoding/json/encode.go#L697-L699)
英文:
You could write your own UnmarshalJSON
method on the *Set
type which would then be used by the json.Encoder
to encode the json data into the Set
. Here's a simple example https://play.golang.org/p/kx1E-jDu5e.
By the way, the reason you're getting the error is because a map key of type interface{}
is not supported by the encoding/json
package. (https://github.com/golang/go/blob/master/src/encoding/json/encode.go#L697-L699)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论