我正在嘗試設置一個從數據庫查詢數據并將其作為 JSON 發送的 Go MySQL 服務器。我的數據庫包含一些新 JSON 類型的列。地圖結構:type Map struct{ Id int `json:"id"` Data string `json:"data"` //This column is stored in the database as a JSON. Which type to use here? Created time.Time `json:"created"` UserId int `json:userid`}從數據庫中獲取數據的函數func GetMap(id int) Map{ var mapId int var data string //which type should this be var userId int var created time.Time err := _getMap.QueryRow(id).Scan(&mapId, &data, &userId, &created) //getMap is a prepared query mapObj := Map{Id:mapId, Data:data, UserId:userId, Created:created} return mapObj}當我像這樣發送這些數據時resp.Header().Set("Content-Type", "application/json; charset=UTF-8")resp.WriteHeader(http.StatusOK)gmap := GetMap(id)err := json.NewEncoder(resp).Encode(gmap); 客戶端收到的 JSON 中的數據被格式化為字符串:{\"field\":\"nowork\"...}我認為問題是由結構定義中的錯誤數據類型引起的,這意味著數據將以錯誤的格式解析。我試圖將數據類型更改為 []uint8、interface{} 和其他一些我認為可能相關的數據類型,但無濟于事。
1 回答

HUH函數
TA貢獻1836條經驗 獲得超4個贊
好的,就像評論中建議的 pregmatch 一樣,我嘗試使用JASON模塊來處理 JSON 解析。令我驚訝的是,它有效:
func GetMap(id int) Map{
var mapId int
var data string
var userId int
var created time.Time
err := _getMap.QueryRow(id).Scan(&mapId, &data, &userId, &created)
if (err != nil){
log.Print(err)
}
dataJSON, _ := jason.NewObjectFromBytes([]byte(data))
mapObj := Map{Id:mapId, Data:dataJSON, UserId:userId, Created:created}
return mapObj
}
在 REST-client 中以正確的格式接收:
{"field":"works!"...}
- 1 回答
- 0 關注
- 197 瀏覽
添加回答
舉報
0/150
提交
取消