Golang json转结构体
来源:互联网 发布:下个学粤语歌软件 编辑:程序博客网 时间:2024/06/07 18:19
json字串
首先 我们来看一下这个json 字串
{ "resp": { "respCode": "000000", "respMsg": "成功", "app": { "appId": "d12abd3da59d47e6bf13893ec43730b8" } }}
结构体拆解
go 内置了json字串的解析包 “encoding/json”
按照json库的分析,其实每一个花括号就是一个结构体
那么拆解的结构体如下:
//代表最里层的结构体type appInfo struct { Appid string `json:"appId"`}//代表第二层的结构体type response struct { RespCode string `json:"respCode"` RespMsg string `json:"respMsg"` AppInfo appInfo `json:"app"`}type JsonResult struct { Resp response `json:"resp"` //代表最外层花括号的结构体 }
结构体的命名必须遵循第一个字母大写,否则json库会忽略掉该成员
这和Go的设计理念一致,结构体中首字母大写的成员,才可被其他对象问
而后面的json:“xxx” xxx则需要和json字串里的名字相符合:
如最外层的 json:”resp” 和json字符串里的“resp”一致
测试
实际的代码解析如下
package mainimport ( "fmt" "encoding/json")type appInfo struct { Appid string `json:"appId"`}type response struct { RespCode string `json:"respCode"` RespMsg string `json:"respMsg"` AppInfo appInfo `json:"app"`}type JsonResult struct { Resp response `json:"resp"`}func main() { jsonstr := `{"resp": {"respCode": "000000","respMsg": "成功","app": {"appId": "d12abd3da59d47e6bf13893ec43730b8"}}}` var JsonRes JsonResult json.Unmarshal(body, &JsonRes) fmt.Println("after parse", JsonRes)}
阅读全文
0 0
- Golang json转结构体
- go、golang结构体对象转Json失败原因总结
- [译]Golang中JSON和结构体的组合使用
- Golang中结构体转byte数组
- golang初始化结构体
- Golang结构体分析
- golang 结构体和 json 相互转换时的 key 匹配问题
- [golang] struct转JSON,解析JSON
- 原 golang 结构体
- Golang结构体和指针
- Rust golang之结构体
- Golang Json
- golang json
- golang 将json串转换为树状结构
- golang API json,struct结构中标签(Tag)的使用
- Golang从入门到精通(十四):Golang结构体
- 跟着猫哥学Golang[6] - 结构体
- golang 动态 实例化 结构体
- java的线程通信wait(),notify(),notifyAll()
- 【有图有真相】android studio Session 'app': Error Installing APK
- axure生成的html,设置未安装插件时不跳转
- 身份证号输入校验
- 第19篇.rar的安装
- Golang json转结构体
- RTP抗丢包传输方案
- Windows系统时间(FILETIME和SYSTEMTIME)
- 使用Intellij IDEA打开MyEclipse项目的具体设置
- JPA 动态查询
- 报错:xml文档结构必须从头到尾包含在一个文档内
- java.lang.IllegalArgumentException: Document base D:\apache-tomcat-6.0.20\webapps\bookstore does not
- D指针和Q指针
- mvc4.5更改为mvc4.0方法总结