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!"...}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效