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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?