dpdbu24262 2014-08-03 22:54
浏览 95
已采纳

Golang-无法解析JSON

I've started learning GO, and i have encountered this issue. I have this code

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
",w)
}

when i run it, it shows this

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

So, the JSON is not parsed into the weather struct.

Any ideas, why do this happens like this?

  • 写回答

3条回答 默认 最新

  • douwenan9849 2014-08-03 23:03
    关注

    By quessing, i found, that this code works:

    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
    ",w)
    }
    

    So, the struct field names have to be Capitalized to work properly!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?