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条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配