cast
cast copied to clipboard
ToStringMapString is unable to cast map[string][]interface{} and error is omitted
Here is my sample code. I tried to turn SampleReq into a map[string]string. However,map["array"] turns out to be empty. I checked the code and found ToStringE() is unable to handle a slice and the error is omitted in the call stack.
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/spf13/cast"
)
type SampleReq struct {
SampleString string `json:"string"`
IntArray []int32 `json:"array"`
}
func main() {
req := &SampleReq{
SampleString: "string",
IntArray: append(make([]int32, 0), 123),
}
reqStr, _ := json.Marshal(req)
d := json.NewDecoder(bytes.NewReader(reqStr))
d.UseNumber()
var mapResult map[string]interface{}
_ = d.Decode(&mapResult)
castResult := cast.ToStringMapString(mapResult)
fmt.Printf("before cast %+v, after cast:%+v", mapResult, castResult) // map["array"] is lost
// a temporary fix
b, _ := json.Marshal(mapResult["array"])
castResult["array"] = string(b)
}