dpxw7293 2014-07-05 05:33
浏览 8
已采纳

如何在golang中解析JSON?

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条回答 默认 最新

  • douchen4534 2014-07-05 05:38
    关注

    Two problems with your code.

    1. You need to export fields or Marshal won't work, read about it here.
    2. Your package must be called main or func main won'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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?