반응형
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
반응형
'programing' 카테고리의 다른 글
AngularJS - 디렉티브의 링크 기능에서 격리된 스코프에 액세스합니다. (0) | 2023.04.04 |
---|---|
리액트 테스트 라이브러리를 사용할 때 구성 요소가 올바른 소품으로 렌더링되는지 테스트하는 방법은 무엇입니까? (0) | 2023.04.04 |
역할 편집자가 workdress에서 woocommerce 분류를 관리할 수 있도록 하려면 어떻게 해야 합니까? (0) | 2023.04.04 |
src/main/resources 폴더에서 프리마커 템플릿 파일을 읽는 방법 (0) | 2023.04.04 |
Wordpress admin menu messed (0) | 2023.04.04 |