dongyun8891 2016-08-28 19:29
浏览 50
已采纳

在Go REST-API中传输MySQL JSON数据类型

I'm trying to set up a Go MySQL server that queries data from the database and sends it as a JSON. My database contains some columns that are in the new JSON type.

The Map struct:

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

The function to fetch data from database

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

}

When I send this data out like this

resp.Header().Set("Content-Type", "application/json; charset=UTF-8")
resp.WriteHeader(http.StatusOK)
gmap := GetMap(id)

err := json.NewEncoder(resp).Encode(gmap); 

The Data in the JSON that the client receives is formatted as a string:

{\"field\":\"nowork\"...}

I think the problem is caused by a wrong datatype in the struct definition, which means that the Data will be parsed in the wrong format.

I have tried to change the datatype to []uint8, interface{} and some others that I thought could be relevant, but to no avail.

  • 写回答

1条回答 默认 最新

  • douniao7308 2016-08-29 13:33
    关注

    Ok, like pregmatch suggested in a comment, I tried using the JASON module to handle the JSON parse. To my great surprise, it works:

    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
    
    }
    

    In the REST-client is received in the proper format:

    {"field":"works!"...}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置