JSON 整数在应该是值时返回 0

我有以下 JSON 文件并尝试解析它。


{

"coord":

{

"lon":-121.31,

"lat":38.7},

"weather":[

{

"id":800,

"main":"Clear",

"description":"clear sky",

"icon":"01d"}

],

"base":"stations",

"main":

{

"temp":73.26,

"pressure":1018,

"humidity":17,

"temp_min":68,

"temp_max":77},

预期输出为:

当前温度:73

今日最低点:68

今日最高点:77

当前湿度:17%


但它反而返回:

当前温度:0

今天的最低价:0

今天的最高价:0

当前湿度:0%


这是我试图用来获得所需回报的代码:


package main


import (

    "encoding/json"

    "fmt"

    "io/ioutil"

    "os"

    "strconv"

)



type Daily struct {

    Currenttemp int `json:"temp"`

    Mintemp     int `json:"temp_min"`

    Maxtemp     int `json:"temp_max"`

    Humidity    int `json:"humidity"`

}



func main() {

    jsonFile, err := os.Open("jsontest1.json")

    if err != nil {

        fmt.Println(err)

    }


    fmt.Println("Successfully Opened jsontest1.json")


    defer jsonFile.Close()


    byteValue, _ := ioutil.ReadAll(jsonFile)


    var daily Daily


    json.Unmarshal(byteValue, &daily)



    fmt.Println("Current Temperature:"+strconv.Itoa(daily.Currenttemp))

    fmt.Println("Today's Low:"+strconv.Itoa(daily.Mintemp))

    fmt.Println("Today's High:"+strconv.Itoa(daily.Maxtemp))

    fmt.Println("Current Humidity:"+strconv.Itoa(daily.Humidity)+"%")



}

我缺少什么?


斯蒂芬大帝
浏览 83回答 1
1回答

侃侃无极

首先,您的示例 JSON 输入格式错误:它},以}}. 这会导致json.Unmarshal返回错误:unexpected EOF解决这个问题会导致更多问题,其中许多问题人们已经在评论中指出。例如,您的输入与您的 不具有相同的结构struct,并且 JSON 数字解码为float64,而不是int。其中一个值(带有键的值"temp")是73.26,它不是整数。我有点不喜欢悄悄地忽略未知字段,所以我喜欢使用json.Decoder不允许未知字段的 a 。这有助于确保您不会因使用错误的标签或错误级别的标签而搞乱数据结构,因为当您这样做时,您只会将所有缺失的字段设置为零。所以我喜欢添加一个“忽略”解码器来显式忽略字段:type ignored [0]bytefunc (i *ignored) UnmarshalJSON([]byte) error {    return nil}然后,您可以声明类型字段ignored,但仍然给它们 json 标签(尽管默认匹配字段名称往往就足够了):type overall struct {    Coord   ignored    Weather ignored    Base    ignored    Main    Daily}如果您确实想直接解组为整数类型,则需要再次花哨,就像我在示例中所做的那样。直接解组可能更明智float64。如果您这样做(使用float64而不添加特殊类型只是为了忽略某些字段),您可以放弃使用json.NewDecoder.您可以变得更奇特,并使用指针来判断您的字段是否已填写,但我在示例中没有这样做。我剪掉了文件读取(以及对读取调用缺乏错误检查)并使用硬编码输入数据。解码确实有效的最终版本位于Go Playground 上。
打开App,查看更多内容
随时随地看视频慕课网APP