donglu5612 2016-02-27 19:57
浏览 57
已采纳

在Golang JSON POST请求中编组为NonString类型

I'm having a little bit of trouble handling types in Golang. I'm making a POST router.

Consider the following struct:

type DataBlob struct {
    Timestamp string
    Metric_Id int `json:"id,string,omitempty"`
    Value float32 `json:"id,string,omitempty"`
    Stderr float32 `json:"id,string,omitempty"`
}

This is my POST router using json.Unmarshal() from a decoded stream:

func Post(w http.ResponseWriter, req * http.Request) {
    body, err := ioutil.ReadAll(req.Body)
    if err != nil {
        panic()
    }

    var t DataBlob
    err = json.Unmarshal(body, &t)
    if err != nil {
        panic()
    }

    fmt.Printf("%s
", t.Timestamp)
    fmt.Printf("%d
", int(t.Metric_Id))
    fmt.Printf("%f
", t.Value)
    fmt.Printf("%f
", t.Stderr)
}

It seems that no matter what I make my values in my POST request:

{
    "timestamp": "2011-05-16 15:36:38",
    "metric_id": "28",
    "value": "4.5",
    "stderr": "8.5"
}

All the non-String values print as 0 or 0.000000, respectively. It also doesn't matter if I try to type convert inline after-the-fact, as I did with t.Metric_Id in the example.

If I edit my struct to just handle string types, the values print correctly.

I also wrote a version of the POST router using json.NewDecoder():

func Post(w http.ResponseWriter, req * http.Request) {
    decoder := json.NewDecoder(req.Body)

    var t DataBlob
    err := decoder.Decode(&t)
    if err != nil {
        panic()
    }

    fmt.Printf("%s
", t.Timestamp)
    fmt.Printf("%d
", t.Metric_Id)
    fmt.Printf("%f
", t.Value)
    fmt.Printf("%f
", t.Stderr)
}

This is building off of functionality described in this answer, although the solution doesn't appear to work.

I appreciate your help!

  • 写回答

1条回答 默认 最新

  • doupa2871 2016-02-27 21:39
    关注

    You need to change the names of your Datablob values. You've told the JSON decoder that they're all named "id". You should try something like the following. Also, take a look at the json.Marshal description and how it describes the tags for structs and how the json library handles them. https://golang.org/pkg/encoding/json/#Marshal

    type DataBlob struct {
        Timestamp string
        Metric_Id int `json:"metric_id,string,omitempty"`
        Value float32 `json:"value,string,omitempty"`
        Stderr float32 `json:"stderr,string,omitempty"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 代写uni代码,app唤醒
  • ¥15 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下: