golang json 解析难题
在 json 数据解析过程中,如何将一组字节数组解析成结构体时,新手常常会遇到困难。
问题描述:
package mainimport ( "fmt" jsoniter "github.com/json-iterator/go")type car struct { other []byte `json:"other"`}func main() { j := []byte(`{"other": {"a":[1,2]}}`) json := jsoniter.configcompatiblewithstandardlibrary obj := car{} err := json.unmarshal(j, &obj) if err != nil { fmt.println(err.error()) } else { fmt.println(obj) }}
登录后复制
执行代码会报错:
立即学习“go语言免费学习笔记(深入)”;
main.car.other: base64codec: invalid input, error found in #10 byte of ...|{"other": {"a":[1,2]|..., bigger context ...|{"other": {"a":[1,2]}}|...
登录后复制
解决方案:
在 go 中解析 json 数据时,需要明确指定结构体的完整结构。修改后的代码如下:
package mainimport ( "fmt" jsoniter "github.com/json-iterator/go")type other struct { A []int `json:"a,omitempty"`}// Car 车type Car struct { Other other `json:"other,omitempty"`}func main() { j := []byte(`{"other": {"a":[1,2]}}`) json := jsoniter.ConfigCompatibleWithStandardLibrary obj := Car{} err := json.Unmarshal(j, &obj) if err != nil { fmt.Println(err.Error()) } else { fmt.Printf("%+v", obj) }}
登录后复制
请注意,在 go 中从字符串解析出结构体时,需要写明所有结构体结构,否则会出现解析错误。
以上就是Golang JSON 解析难题:如何将一组字节数组解析成结构体?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2316888.html