golangにおけるjsonデコードについて
前提
-
json decodeまわりをgolangで書いており、質問です。
-
io.Readerのポインタ位置あたりが理解しきれていないのが問題だと思っています。
-
前提となるAPIレスポンス(JSON形式)は下記の通りです。
// 異常時:エラーメッセージだけ返却される { “Message”:{ “msg struct”: ~~, ~~ } } // 正常時:body structが返却される { “Message”:{ “messageType”: ~~, ~~ }, “ResponseBody”:{ “body strcut”: ~~, ~~ } }
問題
- こちらを参考に、ネストしたstructを用意してdecodeしています。
//異常時かどうかチェックするためのstruct type HogeMessages struct { Message []struct { MessageType string `json:"messageType"` ~~ } `json:"Message"` } //正常時のデコード用 type HogeFull struct { Message []struct { MessageType string `json:"messageType"` ~~ } `json:"Message"` Body []struct { someBody string `json:”someBody”` ~~ } `json:”Body”` }
- デコード処理をこのように書いています。
func NewDecodeJson(body io.ReadSeeker) (*HogeFull, error) { var hogeFull HogeFull // Messageをチェック。エラーの場合は、HogeFullのパースができない if !orderLists.IsExistBody(body) { return &HogeFull{}, fmt.Errorf(“not exist”) } //body.Seeker(0,0) //★これを追加すると、エラーが解消する。 //ただし、引数が`io.ReadSeeker`でないと利用できないので、resp.Bodyを引数として渡せない if err := json.NewDecoder(body).Decode(&hogeFull); err != nil { return &HogeFull{}, err } return &HogeFull, nil }
- 実行結果として、下記のエラーが発生しています。
2018/06/29 21:20:49 [TEST] hogeFull=&{[] [] {0 0 0}} panic: runtime error: index out of range [recovered] panic: runtime error: index out of range ~~~
- 上記サンプルの「★」を追加して、offsetを先頭に戻すと成功するようです。ただし、reso.Bodyは、
io.ReadCloser
のため、上記に渡せなくなってします。
ちなみに
- 下記のように
TeeReader()
も使ってみましたが、同様にエラーがでてしまいます。
func NewDecodeJson(body io.Reader) (*HogeFull, error) { var hogeFull HogeFull bufForExam := &bytes.Buffer{} teeBody := io.TeeReader(body, bufForExam) //offsetを変更しないようにcopy // Messageをチェック。エラーの場合は、HogeFullのパースができない if !orderLists.IsExistBody(bufForExam) { return &HogeFull{}, fmt.Errorf(“not exist”) } if err := json.NewDecoder(teeBody).Decode(&hogeFull); err != nil { return &HogeFull{}, err } return &HogeFull, nil }
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/02 11:55
2018/07/02 23:08
2018/07/03 03:47