doulu2011 2018-02-26 09:54
浏览 102
已采纳

json.Unmarshal()如何工作以及如何存储在变量中?

Just started with Go and I have a small doubt from a tutorial I am following. I read that Unmarshall is some kind of JSON encoding, my doubt here is: err = json.Unmarshal(body, &p) why are we assigning the encoded body to err and how is p.Stuff.Fruit getting the value when I can't see anything assigned to p.

Note : produce is different package which contains some type and arrays.*

func main() {
  url := "http://localhost:12337"
  res, err := http.Get(url)
  if err != nil {
    panic(err)
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    panic(err)
  }

  var p produce.Payload

  err = json.Unmarshal(body, &p)  // I cant get this
  if err != nil {
    panic(err)
  }

  // how are these getting the values assigned to them

  fmt.Println(p.Stuff.Fruit)
  fmt.Println(p.Stuff.Veggies)
}
  • 写回答

2条回答 默认 最新

  • 普通网友 2018-02-26 09:56
    关注

    my doubt here is: err = json.Unmarshal(body, &p) why are we assigning the encoded body to err

    You don't. You pass the body to the json.Unmarshal() function, and you assign its return value to the err variable, which tells you if unmarshaling failed (or succeeded if err is nil).

    how is p.Stuff.Fruit getting the value when I can't see anything assigned to p

    You pass the address of p to json.Unmarshal(), so it has a pointer to your variable, and so if it modifies the pointed value (pointed by the pointer), it modifies the same value you have (p).

    See this simple example:

    func change(p *int) {
        *p = 3
    }
    
    func main() {
        var i int
        fmt.Println("Before", i)
        change(&i)
        fmt.Println("After", i)
    }
    

    Output (try it on the Go Playground):

    Before 0
    After 3
    

    In the main() function we don't assign anything to the local variable i, but we pass its address to the change() function, which modifies the pointed value, and so if we print the value of i after the change() call, we see its value changed.

    You pass the address of p to json.Unmarshal(), so it will be capable of modifying the value stored in p. Under the hood, the json package uses reflection (package reflect) to discover the runtime type of p and modify it according to the JSON document you pass to it to parse.

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

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路