【问题标题】:JSON Decoder gives unexpected resultsJSON解码器给出了意想不到的结果
【发布时间】:2013-09-14 20:56:39
【问题描述】:

我有2个结构如下

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
}

所以你可以看到 Job 类型有一个 Crontime 类型的数组

我有一个关于以下功能的发布请求

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 Object 解码为 Job Object

我的请求的 JSON 对象看起来像

{
    "ScheduleTime" : 
    [{
        "second" : 0,
        "minute" : 1,
        "hour" : 10,
        "dayOfMonth" : 1,
        "month" : 1,
        "dayOfWeek" : 2
    }],
    "CallbackUrl" : "SomeUrl",
    "JobDescriptor" : "SendPush"
}

但 Json 解码器无法将请求正文解码为 ScheduleTime,它是 CronTime 的数组。

我得到{[{0 0 0 0 0 0}] SomeUrl SendPush} 作为上述请求的日志输出。但我期待它{[{0 1 10 1 1 2}] SomeUrl SendPush}

谁能告诉我我做错了什么?

【问题讨论】:

  • 我想通了,CronTime 类型的字段需要大写才能导出。
  • 酷,如果您想帮助可能遇到此问题的其他人,您可以在下面回答您自己的问题。

标签: json go


【解决方案1】:

encoding/json 包只会将数据解组到结构的公共字段中。所以有两种选择:

  1. CronTime 的字段重命名为大写以使其公开。
  2. CronTime 实现json.Unmarshaller 接口并编写一个自定义的UnmarshalJSON 实现来解组到私有字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2019-05-19
    • 2017-01-05
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多