go - 如何将字符串转换为结构数组
问题描述
我有一个 json 数组,它被转换成一个字符串。现在我想将字符串映射到结构数组,以便我可以修改字符串 json。下面是我的代码库
type ProcessdetailsEntity struct {
Source []int64 `json:"source"`
Node string `json:"node"`
Targets []int64 `json:"targets"`
Issave bool `json:"isSave"`
Instate []int64 `json:"inState"`
OutState []int64 `json:"outState"`
}
func main() {
var stringJson = "[{\"source\":[-1],\"node\":\"1_1628008588902\",\"targets\":[],\"isSave\":true,\"inState\":[1],\"outState\":[2]},{\"source\":[\"1_1628008588902\",\"5_1628008613446\"],\"node\":\"2_1628008595757\",\"targets\":[],\"isSave\":true,\"inState\":[2,5],\"outState\":[3,6]}]"
in := []byte(stringJson)
detailsEntity := []ProcessdetailsEntity{}
err := json.Unmarshal(in, &detailsEntity)
if err != nil {
log.Print(err)
}
}
现在,当我运行此代码库时,出现错误:
json: cannot unmarshal string into Go struct field ProcessdetailsEntity.source of type int64
如何正确地将字符串映射到 struct 以便我可以修改 json 的inState
andoutState
值?
解决方案
你得到的错误已经很明显了:
无法将字符串解组为 int64 类型的 Go struct 字段 ProcessdetailsEntity.source
这告诉您(至少一个)source
字段似乎具有错误的类型: astring
而不是可以由 a 表示的东西int64
。
因此,让我们检查您的source
字段stringJson
:
"source":[-1]
"source":["1_1628008588902","5_1628008613446"]
如您所见,第二个source
是string
. 因此错误。
要解决这个问题,您需要确保source
是一个int
. 不幸的是,1_1628008588902
并且5_1628008613446
不是 Go 中的有效整数。
我稍微修改了您的 JSON 并修复了您的代码,然后它就可以工作了:
package main
import (
"encoding/json"
"log"
)
type ProcessdetailsEntity struct {
Source []int64 `json:"source"`
Node string `json:"node"`
Targets []int64 `json:"targets"`
Issave bool `json:"isSave"`
Instate []int64 `json:"inState"`
OutState []int64 `json:"outState"`
}
func main() {
var stringJson = `[
{
"source":[-1],
"node":"1_1628008588902",
"targets":[],
"isSave":true,
"inState":[1],
"outState":[2]
},
{
"source":[11628008588902,51628008613446],
"node":"2_1628008595757",
"targets":[],
"isSave":true,
"inState":[2,5],
"outState":[3,6]
}
]`
in := []byte(stringJson)
detailsEntity := []ProcessdetailsEntity{}
err := json.Unmarshal(in, &detailsEntity)
if err != nil {
log.Print(err)
}
}
见: https: //play.golang.org/p/kcrkfRliWJ5
推荐阅读
- ethereum - 保存地址
- sed - Linux sed 搜索带有反斜杠的行
- ruby-on-rails - 尝试用 jest 测试反应组件时无法编译 js.erb 导入的模块
- dns - 我收到“type master”错误;在我的 named.conf 文件中
- here-api - 这里 Maps cors 问题 - 只有本地资源(没有外部资源)
- java - Android 11 运行时存储权限
- python - 为什么存储“for循环”的结果不起作用?
- c++ - 您可以在 C++ 中动态分配带有向量作为字段的类吗?
- google-cloud-platform - Google Cloud 如何对默认服务帐号进行身份验证?
- c++ - 如何在一串字符中找到一个单词,其中字符可能由空格分隔