英文:
How do I parse JSON in golang?
问题
我尝试在golang中解析JSON,但似乎没有起作用。我得到的输出是0,而不是1。我做错了什么?
package main
import (
  "fmt"
  "encoding/json"
)
type MyTypeA struct {
  a int
}
func main() {
  var smthng MyTypeA
  jsonByteArray := []byte(`{"a": 1}`)
  json.Unmarshal(jsonByteArray, &smthng)
  fmt.Println(smthng.a)
}
你的代码有一个问题。在Go中,结构体字段必须以大写字母开头才能被导出和解析。因此,你需要将MyTypeA结构体中的a字段改为大写字母开头的A。
修改后的代码如下:
package main
import (
  "fmt"
  "encoding/json"
)
type MyTypeA struct {
  A int
}
func main() {
  var smthng MyTypeA
  jsonByteArray := []byte(`{"a": 1}`)
  json.Unmarshal(jsonByteArray, &smthng)
  fmt.Println(smthng.A)
}
这样修改后,你应该能够正确解析JSON并打印出1。
英文:
I tried to "Unmarshal" json in golang, but it doesn't seem to be working.
I get 0 printed out instead of 1. What am I doing wrong?
package main
import (
  "fmt"
  "encoding/json"
)
type MyTypeA struct {
  a int
}
func main() {
  var smthng MyTypeA
  jsonByteArray := []byte(`{"a": 1}`)
  json.Unmarshal(jsonByteArray, &smthng)
  fmt.Println(smthng.a)
}
答案1
得分: 4
你的代码有两个问题。
- 你需要导出字段,否则Marshal函数无法正常工作,可以在这里阅读相关信息:http://golang.org/ref/spec#Exported_identifiers。
 - 你的包必须命名为main,否则
func main函数将不会被执行。 
以下是翻译好的代码:
package main
import (
	"encoding/json"
	"fmt"
)
type MyTypeA struct {
	A int
}
func main() {
	var smthng MyTypeA
	jsonByteArray := []byte(`{"a": 1}`)
	json.Unmarshal(jsonByteArray, &smthng)
	fmt.Println(smthng.A)
}
希望对你有帮助!
英文:
Two problems with your code.
- You need to export fields or Marshal won't work, read about it here.
 - Your package must be called main or 
func mainwon't be executed. 
http://play.golang.org/p/lJixko1QML
type MyTypeA struct {
	A int
}
func main() {
	var smthng MyTypeA
	jsonByteArray := []byte(`{"a": 1}`)
	json.Unmarshal(jsonByteArray, &smthng)
	fmt.Println(smthng.A)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论