在Golang中编码Set数据结构

huangapple go评论87阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2017年3月14日 07:41:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/42775388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定