前文 : https://www.cnblogs.com/zengxm/p/13488448.html
https://www.cnblogs.com/zengxm/p/13473340.html
如果業務查詢返回json格式字符串,但是該字符串含有多個map,需要將字符串反序列化到切片結構體中
反序列化的結構體
貌似有個坑,如果內嵌的切片結構體被命名之后反序列化錯誤
mysql查詢代碼
var result []SelectData
SQL := "SELECT u.u_id,u.nickename,u.username, " +
"CONCAT('{\"datas\":[',GROUP_CONCAT('{\"cid\":',c.c_id,',\"title\":\"',c.c_name,'\",\"price\":',c.price,',\"info\":\"',c.info,'\"}'),']}') as datas " +
"FROM users AS u " +
"JOIN curriculums AS c " +
"ON c.u_id = u.u_id " +
"WHERE c.c_name like '%o%' GROUP BY u.u_id"
conn.Raw(SQL).Scan(&result)
返回的結果為多個,resukt為切片,執行循環反序列化
for index,_ := range result{ result[index].JsonStr = strings.Replace(result[index].JsonStr,"\n","",-1) err := json.Unmarshal([]byte(result[index].JsonStr),&result[index].Mid) if err != nil { panic(err) } //fmt.Println(result[index].Mid) /* 反序列化到結構體 {[{102 0 python 學習 20 python <nil> <nil> <nil> 0} {103 0 golang 學習 70.79 go語言 gin框架 <nil> <nil> <nil> 0}]} {[{117 0 測試保存視頻,視頻url保存在阿里雲oss上 9.99 test in <nil> <nil> <nil> 0}]} */ result[index].JsonStr = "" fmt.Println(result[index])
/*
{{100000 acfun 7745742641 0 0 <nil> <nil> 0} {[{102 0 python 學習 20 python <nil> <nil> <nil> 0} {103 0 golang 學習 70.79 go語言 gin框架 <nil> <nil> <nil> 0}]}}
{{100006 giligililllsa666 z99999es 0 0 <nil> <nil> 0} {[{117 0 測試保存視頻,視頻url保存在阿里雲oss上 9.99 test in <nil> <nil> <nil> 0}]}}
*/
}
參考資料:https://stackoverflow.com/questions/21830447/json-cannot-unmarshal-object-into-go-value-of-type