开始学习歌朗.

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?

推荐答案

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

struct 字段必须以大写字母(exported)开头,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来判断 struct 字段.因为reflect不允许访问未导出的 struct 字段,所以JSON包看不到它们的值.

Json相关问答推荐

无法根据vega规范中的条件设置文本 colored颜色

删除JSON文件的特定内容

用于参考的Jolt变换

需要有关在Ffltter应用程序中解码JSON的帮助;未处理的异常:类型不是类型转换中类型的子类型

无法使用Jolt变换在嵌套的JSON中提取值

使用JQ将JSON输出转换为CSV复杂 struct

条件性构建/修改嵌套对象数组

如何按键过滤

JOLT 获取带有动态键的数组

如何配置spring mvc 3在json响应中不返回null对象?

使用基本身份验证通过 CURL 发布 JSON

Angularjs访问本地json文件

如何使用 Newtonsoft.Json 反序列化 JSON 数组

从 Postgres 中的 json 对象中提取键、值

如何使用 Jackson 定义可选的 json 字段

Peewee 模型转 JSON

杰克逊在通用列表中读取 json

确保数组中的项目属性在 Json Schema 中是唯一的?

从 JSON 到 JSONL 的 Python 转换

仅使用字符串和值解析 JSON 对象