golang json.Marshal interface 踩坑

Golang 使用 hprose 调用 php 接口,各类类型不肯定,用了好多interface,而后发现了 json.Marshal 在处理map类型的时候,key 不能是 interface,不然就会报错php

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

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

怎么办呢?架构

还能怎么办,只能不用 interface 作 key 。code

若是遇到接口返回的 key 是 interface 的状况,在输出的时候,用断言判断他的类型,转成正常的 map 或者 struct接口

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

相似这种写法,哦,有点恶心。string

更多架构、PHP、GO相关踩坑实践技巧请关注个人公众号:PHP架构师it

相关文章
相关标签/搜索