有Json标签但没有导出

fro*_*ock 7 json go

开始学习golang.任务:获取Json和Unmarshall.但我错了:

Json tag but not exported
Run Code Online (Sandbox Code Playgroud)

如何导出未导出的字段,然后使用方法实现它?

这是代码:

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)
}
Run Code Online (Sandbox Code Playgroud)

请详细解释struct的错误以及如何获得正确的响应?

Mos*_*vah 20

您正在向未导出的字段添加JSON标记.

必须为JSON包导出 Struct字段才能查看其值.

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"`
}
Run Code Online (Sandbox Code Playgroud)

此要求的根本原因是JSON包用于reflect检查struct字段.由于reflect不允许访问未导出的struct字段,因此JSON包无法查看其值.