douhua1760 2017-10-10 14:57
浏览 447
已采纳

如何使用Go将具有不同类型的一个元素的数组封送为JSON?

I need this result of JSON marshal:

["a", "b", ["c", "d"], "e"]

How correctly to do this in Go?

  • 写回答

2条回答 默认 最新

  • dongxia527680 2017-10-10 15:08
    关注

    The trick to creating a slice/array of mixed types is to use the empty interface type that go offers

    inner := []string{"c", "d"}
    all := []interface{}{"a", "b", inner, "e"}
    

    And then just json.Marshal the interface slice. This works because any and all values implement at least an empty interface. You can use the most bloated object as though it doesn't have any methods/receiver functions to call. That's why people sometimes refer to go's interface{} type as being a "generic" type. A lot of abstract stuff that packages do use interface{} arguments, and then reflection to work out what was actually passed. Just look at the source of the encoding/json package and see how it unmarshals values...

    https://play.golang.org/p/96VVo2F1m7

    Unmarshalling would work in pretty much the same way: you can unmarshal JSON strings into interface{} variables. You may need to use type-assertions and/or reflection to be able to work with the data though. That's why it's probably best to create types...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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