例如:
將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中變量名是不可導(dǎo)出的(首寫字母是小寫的),需要把首寫字母改成大寫
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}]
簡單進(jìn)行修改,修改為:
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"` //指針,指向引用對象;如果不用指針,只是值復(fù)制
SecondFruit *Fruit `json:"second fruit"` //指針,指向引用對象;如果不用指針,只是值復(fù)制
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)
}
運行結(jié)果:
{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}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- react組件中的constructor和super知識點整理
- MapStruct到底是什么?
- Go遍歷struct,map,slice的實現(xiàn)
- golang struct, map, json之間的相互轉(zhuǎn)換
- golang 生成對應(yīng)的數(shù)據(jù)表struct定義操作
- Java MapStruct解了對象映射的毒
- C#調(diào)用C類型dll入?yún)閟truct的問題詳解
- Java Structs框架原理案例詳解