doudou5421 2018-07-10 16:43
浏览 46
已采纳

将清单解组

Moved from python to golang:

jsonBlob := `{ "test" : {"thing":["team1", "team2"]}}`

type other map[string]Myset
type stuff map[string]other
type MySet struct {
    set mapset.Set
}

//Custom unmarshaller
func (s *MySet) UnmarshalJSON(p []byte) error {
    var a []interface{}
    if err := json.Unmarshal(p, &a); err != nil {
        return err
    }
    s.set = mapset.NewSet(a)
    return nil
}

 // Unmarshall it
 var s stuff
 err := json.Unmarshall(jsonBlob, &s)
 if err != nil {
  return err   
}

but it throws: runtime error: hash of unhashable type []interface {}

  • 写回答

1条回答 默认 最新

  • doqpm82240 2018-07-10 17:20
    关注

    Given that the data type you wish to use is an interface, and does not satisfy the json.Unmarshaler interface, you have two options:

    1. Unmarshal to an array, then convert to your preferred type.

    2. Create a custom type, that wraps your preferred type, and provides an UnmarshalJSON method. This is functionally the same as #1, but may be easier to use. Example:

      type MySet struct {
          set mapset.Set
      }
      
      func (s *MySet) UnmarshalJSON(p []byte) error {
          var a []interface{}
          if err := json.Unmarshal(p, &a); err != nil {
              return err
          }
          s.set = mapset.NewSet(a)
          return nil
      }
      

      (Note, this code is untested; it is not meant to be a complete solution, but a guide in the right direction.)

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器