programing

Json 태그는 있지만 내보내지 않음

subpage 2023. 4. 4. 21:18
반응형

Json 태그는 있지만 내보내지 않음

골랑을 공부하기 시작했다.과제: Json과 Unmarshall을 가져옵니다.하지만 내가 실수를 했어

Json tag but not exported

보고되지 않은 필드를 내보낸 후 메서드를 사용하여 구현하려면 어떻게 해야 합니까?

코드는 다음과 같습니다.

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)
}

구조의 문제점과 올바른 대응을 하는 방법에 대해 자세히 설명해 주세요.

내보내지 않은 필드에 JSON 태그를 추가하고 있습니다.

구조 필드는 JSON 패키지의 값을 표시하려면 대문자(내보내기)로 시작해야 합니다.

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"`
}

이 요건의 근본적인 이유는 JSON 패키지가reflect구조 필드를 검사합니다.부터reflect보고되지 않은 구조 필드에 대한 액세스를 허용하지 않으므로 JSON 패키지는 해당 값을 볼 수 없습니다.

언급URL : https://stackoverflow.com/questions/50319404/has-json-tag-but-not-exported

반응형