donglv9813
donglv9813
2018-01-30 16:26

如何将请求正文解码/解组为Golang结构和结构切片?

  • struct

How do I properly unmarshal this in Golang?

{
    "symbol": "ZVZZT.O",
    "params": [{
        "forward": 0,
        "period": 3,
        "ref": "high",
        "indicator": "sma",
        "freq": "day"
    }, {
        "forward": 1,
        "period": 8,
        "ref": "close",
        "indicator": "ema",
        "freq": "week"
    }]
}

into these structs

type Iteration4RequestBody struct {
    Symbol string             `json:"symbol"`
    Params []Iteration4Params `json:"params"`
}

type Iteration4Params struct {
    Forward   int    `json:"forward"`
    Period    int    `json:"period"`
    Ref       string `json:"ref"`
    Indicator string `json:"indicator"`
    Freq      string `json:"freq"`
}

I need to be able to use []Iteration4Params, but right now, this is empty when I decode it

EDIT 2 (NEW CODE I USED)

body, err := ioutil.ReadAll(r.Body)
if err != nil {
    panic(err)
}
var t Iteration4RequestBody
err = json.Unmarshal(body, &t)
if err != nil {
    panic(err)
}
fmt.Println(t)

Result is {ZVZZT.O []}

Edit 3: Works now. Can't remember the last thing I did before it worked though. Never mind. Thanks for all your answers by the way.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答