Go 使用Unmarshal将json赋给struct出错的原因及解决
程序员文章站
2023-08-24 17:56:57
例如:将json:{ "name": "laura" "age": "18"}赋给struct:type personalinfo struct { name string `json:"name"`...
例如:
将json:
{ "name": "laura" "age": "18" }
赋给struct:
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" ] }
go代码:
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}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
下一篇: Python特殊方法整理汇总