亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Go REST-API 中傳輸 MySQL JSON 數據類型

在 Go REST-API 中傳輸 MySQL JSON 數據類型

Go
慕神8447489 2022-03-07 15:48:26
我正在嘗試設置一個從數據庫查詢數據并將其作為 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!"...}


查看完整回答
反對 回復 2022-03-07
  • 1 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號