我正在尝试设置一个Go MySQL服务器,它从数据库中查询数据并将其作为JSON发送。我的数据库包含一些新的JSON类型的列。
Map结构:
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\"...}
我认为这个问题是由struct定义中的错误数据类型引起的,这意味着数据将以错误的格式进行解析。
我尝试将数据类型更改为[]uint8、接口{}和其他一些我认为可能相关的类型,但都无济于事。
发布于 2016-08-29 21:33:30
好的,就像评论中建议的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!"...}
https://stackoverflow.com/questions/39195005
复制相似问题