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 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'