我正在尝试设置一个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中的Data被格式化为字符串:
{"field":"nowork"...}
我认为问题是由结构定义中的错误数据类型引起的,这意味着数据将以错误的格式解析。
我试图将数据类型更改为[]uint8,接口{}和其他一些我认为可能相关的,但无济于事。
Ok,就像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!"...}