在golang中使用Unmarshal将json赋给struct时出错如何解决?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
将json:
{ "name": "Laura" "age": "18" }
type PersonalInfo struct { Name string `json:"name"` Age string `json:"age"` }
person := PersonalInfo{} err := json.Unmarshal(json, &persona)//json为上面的[]byte
1、struct中变量名是不可导出的(首写字母是小写的),需要把首写字母改成大写
2、需要传输person的指针
3、struct中json的名字与json中的名字需要一模一样
补充:Go语言处理JSON之——利用Unmarshal解析json字符串
首先还是从官方文档中的例子:
package main import ( "fmt" "encoding/json" ) type Animal struct { Name string Order string } func main() { var jsonBlob = []byte(`[ {"Name": "Platypus", "Order": "Monotremata"}, {"Name": "Quoll", "Order": "Dasyuromorphia"} ]`) var animals []Animal err := json.Unmarshal(jsonBlob, &animals) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", animals) }
输出:
[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
简单进行修改,修改为:
package main import ( "fmt" "encoding/json" ) type Animal struct { Name string Order string } func main() { var jsonBlob = []byte(`{"Name": "Platypus", "Order": "Monotremata"}`) var animals Animal err := json.Unmarshal(jsonBlob, &animals) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", animals) }
输出:
{Name:Platypus Order:Monotremata}
解析这样的一个json字符串:
{ "first fruit": { "describe":"an apple", "icon":"appleIcon", "name":"apple" }, "second fruit": { "describe":"an orange", "icon":"orangeIcon", "name":"orange" }, "three fruit array": [ "eat 0", "eat 1", "eat 2", "eat 3", "eat 4" ] }
package main import ( "fmt" "encoding/json" ) type Fruit struct { Describe string `json:"describe"` Icon string `json:"icon"` Name string `json:"name"` } type FruitGroup struct { FirstFruit *Fruit `json:"first fruit"` //指针,指向引用对象;如果不用指针,只是值复制 SecondFruit *Fruit `json:"second fruit"` //指针,指向引用对象;如果不用指针,只是值复制 THreeFruitArray []string `json:"three fruit array"` } func main() { var jsonBlob = []byte(`{ "first fruit": { "describe": "an apple", "icon": "appleIcon", "name": "apple" }, "second fruit": { "describe": "an orange", "icon": "appleIcon", "name": "orange" }, "three fruit array": [ "eat 0", "eat 1", "eat 2", "eat 3" ]}`) var fruitGroup FruitGroup err := json.Unmarshal(jsonBlob, &fruitGroup) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+v\n", fruitGroup) fmt.Printf("%+v\n", fruitGroup.FirstFruit) fmt.Printf("%+v\n", fruitGroup.SecondFruit) }
运行结果:
{FirstFruit:0xc00006c5a0 SecondFruit:0xc00006c5d0 THreeFruitArray:[eat 0 eat 1 eat 2 eat 3]} &{Describe:an apple Icon:appleIcon Name:apple} &{Describe:an orange Icon:appleIcon Name:orange}
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。