dtv7174 2018-05-13 18:35
浏览 741
已采纳

有Json标记,但未导出[重复]

This question already has an answer here:

Begining to study golang. Task: Get Json and Unmarshall it. But I get mistake:

Json tag but not exported

How to make unexported fields become exported and then implement it using methods?

Here is the code:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type Time struct {
    time
}
type time struct {
    id                    string  `json:"$id"`
    currentDateTime       string  `json:"currentDateTime,string"`
    utcOffset             float64 `json:"utcOffset,string"`
    isDayLightSavingsTime bool    `json:"isDayLightSavingsTime,string"`
    dayOfTheWeek          string  `json:"dayOfTheWeek,string"`
    timeZoneName          string  `json:"timeZoneName,string"`
    currentFileTime       float64 `json:"currentFileTime,string"`
    ordinalDate           string  `json:"ordinalDate,string"`
    serviceResponse       string  `json:"serviceResponse,string"`
}

func (t *Time) GetTime() (Time, error) {
    result := Time{}

    return result, t.Timenow(result)
}
func (t *Time) Timenow(result interface{}) error {

    res, err := http.Get("http://worldclockapi.com/api/json/utc/now")
    if err != nil {
        fmt.Println("Cannot get Json", err)
    }

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Println("Cannot create Body", err)
    }

    defer res.Body.Close()

    var resultJson interface{}
    return json.Unmarshal(body, &resultJson)

}

func main() {

    var a Time
    t, err := a.GetTime()
    if err != nil {
        fmt.Println("Error ", err)
    }
    fmt.Println("Time:", t)
}

Please explain in details whats wrong with struct and how to get right response?

</div>
  • 写回答

1条回答

  • douhuibo5635 2018-05-13 20:59
    关注

    You're adding a JSON tag to a field that isn't exported.

    Struct fields must start with upper case letter (exported) for the JSON package to see their value.

    struct A struct {
        // Unexported struct fields are invisible to the JSON package.
        // Export a field by starting it with an uppercase letter.
        unexported string
    
        // {"Exported": ""}
        Exported string
    
        // {"custom_name": ""}
        CustomName string `json:"custom_name"`
    }
    

    The underlying reason for this requirement is that the JSON package uses reflect to inspect struct fields. Since reflect doesn't allow access to unexported struct fields, the JSON package can't see their value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复