dongxia4880 2013-09-14 20:56
浏览 45

JSON解码器产生意外结果

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条回答 默认 最新

  • douxueke5653 2013-09-16 02:35
    关注

    The encoding/json package will only unmarshal data into public fields of a structure. So there are two options:

    1. Rename the fields of CronTime to upper case to make them public.
    2. Make CronTime implement the json.Unmarshaller interface and write a custom UnmarshalJSON implementation that unmarshals to the private fields.
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类