Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JSON解码器给出了意外的结果_Json_Go - Fatal编程技术网

JSON解码器给出了意外的结果

JSON解码器给出了意外的结果,json,go,Json,Go,我有如下两个结构 type Job struct { // Id int ScheduleTime []CronTime CallbackUrl string JobDescriptor string } type CronTime struct { second int minute int hour int dayOfMonth int month in

我有如下两个结构

type Job struct {
    // Id            int
    ScheduleTime  []CronTime
    CallbackUrl   string
    JobDescriptor string
}

type CronTime struct {
    second     int
    minute     int
    hour       int
    dayOfMonth int
    month      int
    dayOfWeek  int
}
如您所见,作业类型有一个类型为
Crontime

我有一个post请求,它涉及到以下函数

func ScheduleJob(w http.ResponseWriter, r *http.Request) {
    log.Println("Schedule a Job")
    addResponseHeaders(w)
    decoder := json.NewDecoder(r.Body)
    var job *models.Job
    err := decoder.Decode(&job)
    if err != nil {
        http.Error(w, "Failed to get request Body", http.StatusBadRequest)
        return
    }
    log.Println(job)
    fmt.Fprintf(w, "Job Posted Successfully to %s", r.URL.Path)
}
我正在尝试将请求
Body
对象解码为
Job
对象

请求的JSON对象如下所示

{
    "ScheduleTime" : 
    [{
        "second" : 0,
        "minute" : 1,
        "hour" : 10,
        "dayOfMonth" : 1,
        "month" : 1,
        "dayOfWeek" : 2
    }],
    "CallbackUrl" : "SomeUrl",
    "JobDescriptor" : "SendPush"
}
但是Json解码器无法将请求正文解码为
ScheduleTime
,它是
CronTime
的数组

我获得
{[{0 0}]SomeUrl SendPush}
作为上述请求的日志输出。但是我希望它
{[{011010}]SomeUrl SendPush}


有人能告诉我我做错了什么吗?

编码/json包只会将数据解压到结构的公共字段中。因此有两种选择:

  • CronTime
    的字段重命名为大写,使其公开
  • 使
    CronTime
    实现
    json.Unmarshaller
    接口,并编写一个自定义
    UnmarshalJSON
    实现,该实现将解组到私有字段

  • 我明白了,CronTime类型的字段需要大写,以便导出。很酷,如果你想帮助其他可能遇到这种情况的人,你可以回答下面的问题。