转换顺序:先将struct结构体转为map,再将map转为string字符串
struct --> map --> string
type demo struct {
Id string
Name string
}
func main() {
demos := [{"Id":"1","Name":"zs"},{"Id":"2","Name":"ls"},{"Id":"3","Name":"ww"}]
for _, v := range demos {
tmpdata := Struct2Map(v)
str, err := json.Marshal(tmpdata)
if err != nil {
fmt.Println(err)
}
fmt.println(string(str))
}
}
//结构体转为map
func Struct2Map(obj interface{}) map[string]interface{} {
t := reflect.TypeOf(obj)
v := reflect.ValueOf(obj)
var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
data[t.Field(i).Name] = v.Field(i).Interface()
}
return data
}