Go:无法解组?

huangapple go评论106阅读模式
英文:

Go: Can't unmarshall?

问题

package main

import "fmt"
import "encoding/json"

func main() {
m := make(map[string]string)
m["name"] = "Test"

  1. j, _ := json.Marshal(m)
  2. fmt.Println(string(j))
  3. var unmarshalled map[string]string
  4. _ = json.Unmarshal(j, &unmarshalled)
  5. fmt.Println(unmarshalled)

}

unmarshalled 应该被填充上 JSON 数据 j

英文:
  1. package main
  2. import "fmt"
  3. import "encoding/json"
  4. func main() {
  5. m := make(map[string]string)
  6. m["name"] = "Test"
  7. j, _ := json.Marshal(m)
  8. fmt.Println(string(j))
  9. var unmarshalled map[string]string
  10. _ = json.Unmarshal(j, unmarshalled)
  11. fmt.Println(unmarshalled)
  12. }

Shouldn't unmarshalled be filled with the json data j

答案1

得分: 6

不要忽视你的错误

json: Unmarshal(非指针map[string]string)

unmarshaled需要是一个指针:

err := json.Unmarshal(j, &unmarshalled)

英文:

Don't ignore your errors

  1. json: Unmarshal(non-pointer map[string]string)

unmarshaled needs to be a pointer:

  1. err := json.Unmarshal(j, &unmarshalled)

huangapple
  • 本文由 发表于 2014年11月27日 05:54:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/27159556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定