英文:
JSON Decoder gives unexpected results
问题
我有两个如下所示的结构体:
type Job struct {
ScheduleTime []CronTime
CallbackUrl string
JobDescriptor string
}
type CronTime struct {
second int
minute int
hour int
dayOfMonth int
month int
dayOfWeek int
}
如你所见,Job类型有一个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解码器无法将请求的Body解码为CronTime类型的数组ScheduleTime。
对于上述请求,我得到的日志输出是[{[0 0 0 0 0 0}] SomeUrl SendPush]
,但我期望得到[{[0 1 10 1 1 2}] SomeUrl SendPush]
。
请问有人可以告诉我我做错了什么吗?
英文:
I've 2 structs as follows
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
}
So as you can see Job type has an Array of type Crontime
I've a post request which comes to following function
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)
}
And I'm trying to decode the request Body
Object to Job
Object
my JSON object for request looks like
{
"ScheduleTime" :
[{
"second" : 0,
"minute" : 1,
"hour" : 10,
"dayOfMonth" : 1,
"month" : 1,
"dayOfWeek" : 2
}],
"CallbackUrl" : "SomeUrl",
"JobDescriptor" : "SendPush"
}
But the Json Decoder is not able to decode the request Body to the ScheduleTime
which is an Array of CronTime
.
I get {[{0 0 0 0 0 0}] SomeUrl SendPush}
as my log output for the above request. But I'm expecting it to {[{0 1 10 1 1 2}] SomeUrl SendPush}
Can someone please tell me what im doing wrong?
答案1
得分: 2
encoding/json
包只会将数据解组到结构体的公共字段中。因此有两个选项:
- 将
CronTime
的字段重命名为大写,使它们变为公共字段。 - 让
CronTime
实现json.Unmarshaller
接口,并编写一个自定义的UnmarshalJSON
实现,将数据解组到私有字段中。
英文:
The encoding/json
package will only unmarshal data into public fields of a structure. So there are two options:
- Rename the fields of
CronTime
to upper case to make them public. - Make
CronTime
implement thejson.Unmarshaller
interface and write a customUnmarshalJSON
implementation that unmarshals to the private fields.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论