dongyun8891 2016-08-28 11: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 05: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!"...}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部