dtz46697 2017-03-13 23:41
浏览 43
已采纳

在Golang中编码设置数据结构

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条回答 默认 最新

  • dpmrakfbx820320638 2017-03-14 00:24
    关注

    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)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式