Reputation: 21
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?
Upvotes: 2
Views: 138
Reputation: 43899
The encoding/json
package will only unmarshal data into public fields of a structure. So there are two options:
CronTime
to upper case to make them public.CronTime
implement the json.Unmarshaller
interface and write a custom UnmarshalJSON
implementation that unmarshals to the private fields.Upvotes: 2