上一篇文章中(地址为:https://blog.youkuaiyun.com/hp_cpp/article/details/101052036),我们最后留了个实例,就是生成这样的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"
"os"
)
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() {
firstFruit := new(Fruit) //指针
firstFruit.Describe = "an apple"
firstFruit.Icon = "appleIcon"
firstFruit.Name = "apple"
secondFruit := new(Fruit) //指针
secondFruit.Describe = "an orange"
secondFruit.Icon = "appleIcon"
secondFruit.Name = "orange"
fruitGroup := FruitGroup{}
fruitGroup.THreeFruitArray = []string{"eat 0","eat 1","eat 2","eat 3"}
fruitGroup.FirstFruit = firstFruit //指针,避免了拷贝
fruitGroup.SecondFruit = secondFruit //指针,避免了拷贝
//方式一
// b, err := json.Marshal(fruitGroup)
// if err != nil {
// fmt.Println("error:", err)
// }
// fmt.Println(string(b))
//输出结果:(输出的结果没有换行,这里人为加上换行是为了方便查看)
//{"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"]}
//方式二
//第二个参数表示的添加的前缀,第三个参数表示缩进四个空格;这两个参数你都可以修改为其他字符串
output, err := json.MarshalIndent(fruitGroup, "", " ")
if err != nil {
fmt.Printf("error: %v\n", err)
}
os.Stdout.Write(output)
}
输出结果:
{
"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"
]
}
参考:
golang中json与struct中tag
GO :json解析及生成json
Go – 在Go语言中使用JSON struct