Skip to content

ToStringMapString is unable to cast map[string][]interface{} and error is omitted #159

Description

@Battery233

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)
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions