sql-server - MSSQL JSON 自动转 Go 结构
问题描述
我正在尝试使用 MSSQL JSON AUTO 轻松地从查询转到 Go Struct。返回的数据看起来 jsony,但在将其从字符串转换为我想要的已知结构时遇到了麻烦。
func main() {
type LOBData struct {
COB_ID int `json:"COB_ID"`
GrossLoss float64 `json:"GrossLoss"`
}
type ResultData struct {
YearID int `json:"YearID"`
EventID int `json:"EventID"`
Modelcode int `json:"modelcode"`
Industry float64 `json:"Industry"`
LOB []LOBData `json:"y"`
}
db, err := sql.Open("sqlserver", ConnString())
checkErr(err)
defer db.Close()
var result string
err = db.QueryRow(`
SELECT i.YearID, i.EventID, i.modelcode, totalloss as Industry, y.COB_ID, y.GrossLoss
FROM dbo.CS_IndustryLossv8_7938 AS i INNER JOIN
dbo.Tb_YLT AS y ON i.YearID = y.YearID AND i.EventID = y.EventID AND i.modelcode = y.Modelcode
where YLT_DVID=25
FOR JSON AUTO`).Scan(&result)
fmt.Println(result)
YLT:= ResultData{}
//var YLT []ResultData
err=json.Unmarshal([]byte(result), &YLT)
checkErr(err)
fmt.Println(YLT)
}
fmt.Printlin(result) 打印:
[{"YearID":7687,"EventID":101900,"modelcode":41,"Industry":1.176648913256758e+010,"y":[{"COB_ID":5,"GrossLoss":6.729697615695682e+003}]},.....
但 fmt.Println(YLT) 返回:
{0 0 0 0 []}
我收到“json 输入意外结束”的错误。
虽然 Go 没有字符串限制,但 MSSQL 有 8,000 个字符。如果我将查询限制在前 3 行并使用var YLT []ResultData
它就可以了。无论如何使用 MSSQL 和 Go 来做这件事,还是我应该使用不同的服务器技术?
解决方案
道歉......找到了答案,与网格输出不同,MSSQL 将结果拆分为多行,而不是需要连接起来。
FOR JSON 子句的输出 FOR JSON 子句的输出具有以下特征:
结果集包含单个列。
一个小的结果集可能包含一行。大型结果集将长 JSON 字符串拆分为多行。默认情况下,当输出设置为“结果到网格”时,SQL Server Management Studio (SSMS) 会将结果串联到一行中。SSMS 状态栏显示实际的行数。其他客户端应用程序可能需要代码通过连接多行的内容将冗长的结果重新组合成一个有效的 JSON 字符串。有关 C# 应用程序中此代码的示例,请参阅在 C# 客户端应用程序中使用 FOR JSON 输出。
推荐阅读
- excel - 如何在 Excel 中使用 COUNTIF 进行条件格式设置
- android - 如何从作为上下文传递给它的类中访问片段方法
- r - 默认情况下如何为 R 中的用户定义函数分配参数?
- node.js - 在单台机器上运行多个 docker 容器的性能
- c# - Checkmarx 扫描中的不安全对象绑定
- amazon-web-services - 如何通过在多个 AWS 实例上运行 Jmeter 测试来对 10 万唯一用户的系统进行负载测试?
- javascript - youtube 视频的自定义 JS,需要声音才能与自动播放一起使用
- python - Pyinstaller - 在 dist 中包含空文件夹
- java - 易失性写入是否也会刷新非易失性写入?
- java - 如何在流批处理流连接中定义连接条件?