doufu6504 2018-03-23 00:24
浏览 106
已采纳

为什么在接口中添加func会导致json.Unmarshal失败?

Why does this fail with the error :

json: cannot unmarshal object into Go struct field Person.spouse of type main.Spouse

type Spouse interface {
    Name() // Adding this causes an error
}

type Address interface {
}

type Person struct {
    Name string   `json:"name"`
    A    *Address `json:"address"`
    S    *Spouse  `json:"spouse"`
}

func main() {
    b := []byte(`{
     "name":"sarah", 
     "address":{
         "street":"101 main" 
         }, 
     "spouse":{
         "name":"joe"
         }
     }
    `)

    p := &Person{}
    if err := json.Unmarshal(b, p); err != nil {
        fmt.Printf("%s", err)
    }
}

Looking at the docs, I don't see why adding a function in an interface would cause an error. I was expecting json.Unmarshal to simply ignore the Name() function since it's not part of the list processed by json.Unmarshal.

Here is the code in go playground.

go version go1.10 darwin/amd64

  • 写回答

2条回答 默认 最新

  • douyuan5600 2018-03-23 01:46
    关注

    From the fine manual:

    func Unmarshal
    [...]
    To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

    bool, for JSON booleans
    float64, for JSON numbers
    string, for JSON strings
    []interface{}, for JSON arrays
    map[string]interface{}, for JSON objects
    nil for JSON null
    

    You're trying to unmarshal a JSON object into an interface so the value behind that interface is going to be a map[string]interface{} to represent the key/value pairs. But map[string]interface{} doesn't have a Name() method so it doesn't implement your Spouse interface.

    If we simplify your example a little and get rid of the Name() method we can see what's going on:

    type Spouse interface {
    }
    
    type Person struct {
        S *Spouse `json:"spouse"`
    }
    
    func main() {
        b := []byte(`{"spouse":{ "name":"joe" } }`)
    
        p := &Person{}
        if err := json.Unmarshal(b, p); err != nil {
            fmt.Printf("%s", err)
        }
        spouse := (*p.S).(map[string]interface{})
        fmt.Printf("%+v
    ", spouse)
    }
    

    spouse is a map[string]interface{} as documented.

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

报告相同问题?

悬赏问题

  • ¥15 esp8266控制共阳极wrgb灯板无法关闭所有led灯
  • ¥100 python读取速度问题
  • ¥15 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?
  • ¥20 关于#c++#的问题:水果店管理系统
  • ¥30 dbLinq最新版linq sqlite
  • ¥20 对D盘进行分盘之前没有将visual studio2022卸载掉,现在该如何下载回来
  • ¥15 完成虚拟机环境配置,还有安装kettle
  • ¥15 2024年全国大学生数据分析大赛A题:直播带货与电商产品的大数据分析 问题5. 请设计一份优惠券的投放策略,需要考虑优惠券的数量、优惠券的金额、投放时间段和投放商品种类等因素。求具体的python代码