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类型的字段需要大写,以便导出。很酷,如果你想帮助其他可能遇到这种情况的人,你可以回答下面的问题。