1. 程式人生 > >golang json.Marshal interface 踩坑

golang json.Marshal interface 踩坑

Golang 使用 hprose 呼叫 php 介面,各種型別不確定,用了好多interface,然後發現了 json.Marshal 在處理map型別的時候,key 不能是 interface,否則就會報錯


package main
import (
    "encoding/json"
    "fmt"
)
func main() {
    m := make(map[interface{}]interface{})
    m["k1"] = "ddd"
    m["k2"] = "ddd"
    b, err := json.Marshal(m)
    if err != nil
{ fmt.Println(err) return } fmt.Println(string(b)) }

輸出


json: unsupported type: map[interface {}]interface {}

怎麼辦呢?

還能怎麼辦,只能不用 interface 做 key 。

如果遇到介面返回的 key 是 interface 的情況,在輸出的時候,用斷言判斷他的型別,轉成正常的 map 或者 struct


switch i.(type) {
case int:
    v = strconv.Itoa(i.(int
)) case string: v = k.(string) …… }

類似這種寫法,哦,有點噁心。

更多架構、PHP、GO相關踩坑實踐技巧請關注我的公眾號:PHP架構師