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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题