Golang - 无法解析JSON

时间:2014-08-03 22:54:04

标签: json go unmarshalling

我开始学习GO,我遇到过这个问题。 我有这个代码

package main

import (
  "fmt"
  "encoding/json"
//  "net/html"
)


func main(){
  type Weather struct {
    name string
    cod float64
    dt float64
    id float64
  }

  var rawWeather = []byte(`{"name":"London","cod":200,"dt":1407100800,"id":2643743}`)
  var w Weather
  err := json.Unmarshal(rawWeather, &w)
  if err != nil {
    fmt.Println("Some error", err)
  }
  fmt.Printf("%+v\n",w)
}

当我运行它时,它显示了这个

[nap@rhel projects]$ go run euler.go 
{name: cod:0 dt:0 id:0}

因此,JSON未被解析为天气结构。

任何想法,为什么会这样发生?

3 个答案:

答案 0 :(得分:6)

您需要将结构字段大写。 E.g:

Name string
Cod  float64
// etc..

这是因为在尝试解组时,json包不会看到它们。

游乐场链接:http://play.golang.org/p/cOJD4itfIS

答案 1 :(得分:0)

通过quessing,我发现,这段代码有效:

package main

import (
  "fmt"
  "encoding/json"
//  "net/html"
)


func main(){
  type Weather struct {
    Name string
    Cod float64
    Dt float64
    Id float64
  }

  var rawWeather = []byte(`[{"name":"London","cod":200,"dt":1407100800,"id":2643743}]`)
  var w []Weather
  err := json.Unmarshal(rawWeather, &w)
  if err != nil {
    fmt.Println("Some error", err)
  }
  fmt.Printf("%+v\n",w)
}

因此,结构字段名称必须大写才能正常工作!

答案 2 :(得分:0)

这是因为Weather不会导出任何字段。这;

type Weather struct {
   name string
   cod float64
   dt float64
   id float64
}

需要;

type Weather struct {
   Name string
   Cod float64
   Dt float64
   Id float64
}

如果未导出字段,则json包将无法访问它。您可以在http://blog.golang.org/json-and-go找到有关它的更多信息,但简短版本是;

“json包只访问struct类型的导出字段(以大写字母开头的字段)。因此,只有结构的导出字段才会出现在JSON输出中。”

相关问题