
golang json 解析难题
在 json 数据解析过程中,如何将一组字节数组解析成结构体时,新手常常会遇到困难。
问题描述:
package main
import (
"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 main
import (
"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\n", obj)
}
}请注意,在 go 中从字符串解析出结构体时,需要写明所有结构体结构,否则会出现解析错误。
以上就是Golang JSON 解析难题:如何将一组字节数组解析成结构体?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号