反序列化为map [string] interface {}作为具体的地图类型

type Foo struct {
    M map[string]interface{} `json:"m"`
}

type Bar struct {
    I int `json:"i"`
}

type Bar2 struct {
    S string `json:"s"`
}


func do() {
    concreteFoo1 := Foo {
        M: make(map[string]Bar),
    }
    json.Unmarshal([]byte(`{"m": {"a": { "i": 1 }}}`), &concreteFoo1)

    concreteFoo2 := Foo {
        M: make(map[string]Bar2),
    }

    json.Unmarshal([]byte(`{"m": {"a": { "s": "hello" }}}`), &concreteFoo2)

}

fails to compile with:

cannot use make(map[string]Bar) (type map[string]Bar) as type map[string]interface {} in field value

cannot use make(map[string]Bar2) (type map[string]Bar2) as type map[string]interface {} in field value

How can I get this to compile, and support both variants of Foo?

查看全部
douzaipou3327
douzaipou3327
2017/11/21 04:06
  • json
  • 点赞
  • 收藏
  • 回答
    私信

5个回复