首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Go REST- MySQL中传输API JSON数据类型

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

Stack Overflow用户
提问于 2016-08-29 03:29:44
回答 1查看 1.4K关注 0票数 0

我正在尝试设置一个Go MySQL服务器,它从数据库中查询数据并将其作为JSON发送。我的数据库包含一些新的JSON类型的列。

Map结构:

代码语言:javascript
运行
复制
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`
}

从数据库获取数据的函数

代码语言:javascript
运行
复制
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

}

当我像这样发送这些数据时

代码语言:javascript
运行
复制
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\"...}

我认为这个问题是由struct定义中的错误数据类型引起的,这意味着数据将以错误的格式进行解析。

我尝试将数据类型更改为[]uint8、接口{}和其他一些我认为可能相关的类型,但都无济于事。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-29 21:33:30

好的,就像评论中建议的pregmatch一样,我尝试使用JASON模块来处理JSON解析。令我大吃一惊的是,它是有效的:

代码语言:javascript
运行
复制
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中,以正确的格式接收:

代码语言:javascript
运行
复制
{"field":"works!"...}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39195005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档