教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 golang json[]

golang json[]

发布时间:2021-04-14   编辑:jiaochengji.com
教程集为您提供golang json[]等资源,欢迎您收藏本站,我们将为您提供最新的golang json[]资源

  golang 的json库利用反射机制,能很方便处理结构体与json字串之间的转换。

  json数组格式:

[
	{
		"riskType": [
			2,
			3
		],
		"uid": "74f6881b-6e2d-4bf5-8671-f2dedd4b226c",
		"level": 4,
		"ip": "110.213.0.151"
	},
	{
		"riskType": [
			1,
			2
		],
		"uid": "5ce35879-423f-4037-9551-d46e7eea3c5f",
		"level": 4,
		"ip": "42.234.88.4"
	}
]

  golang通过json库将json数组转化为结构体数组:

type RiskInfo struct {
	Ip         string `json:"ip"`
	Level      int32  `json:"level"`
	RiskType   []int32 `json:"riskType"`
	Uid      string    `json:"uid"`
}

// 结构数组
var Msg2 []RiskInfo
err = json.Unmarshal([]byte(str), &Msg2)
if err != nil {
	fmt.Printf("err: %v\n", err)
	return
}

 上述代码运行偶尔会出现无法解析的问题,报错:

err: json: cannot unmarshal string into Go struct field RiskInfo.riskType of type []int32

riskType 字段无法解析,打印出错json串,发现:

[
	{
		"riskType": "",  // 居然为空字符串
		"uid": "74f6881b-6e2d-4bf5-8671-f2dedd4b226c",
		"level": 4,
		"ip": "110.213.0.151"
	}
]

接收到的json格式不规范,应该统一为 "riskType": [] 数组格式针对这种非规范json格式,岂不是没解了。别急,golang 的 interface{} 可以表示任意类型。

解决方案:更换riskType为 interface{}

type RiskInfo struct {
	Ip       string `json:"ip"`
	Level    int32  `json:"level"`
	RiskType interface{} `json:"riskType"`	// 修改为空类型
	Uid      string      `json:"uid"`
}

 

 

 

 

 

 

 

 

到此这篇关于“golang json[]”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
Golang解析json数据之延迟解码
golang json[]
golang json inline用法
Golang的 Json string和Map互相转换
Golang json string和Map互相转换
golang中struct字段
go 语言 生成json字符串数组
go json数据转发
Go 学习笔记 09 | Golang 结构体与 JSON 互相转换
Golang JSON-序列化map,切片(slice),结构体(struct)

上一篇:Go Everyday 下一篇:go基础算法思想
[关闭]
~ ~