Go语言中通过encoding/json包对JSON串进行处理:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60package main
import (
"fmt"
"encoding/json"
)
//构造总的JSON串结构体
type GoJson struct {
Name string
Type string
Properties Properties
}
//构造内部JSON串结构体
type Properties struct {
Slice string
Array string
Interface string
Struct string
}
func main() {
//解析JSON串
//待解析的JSON串
jsonStr := `{
"name": "go",
"type": "static",
"properties": {
"slice": "切片",
"array": "数组",
"interface": "接口",
"struct": "结构体"
}
}`
goJson := GoJson{}
err := json.Unmarshal([]byte(jsonStr), &goJson)
if err != nil {
fmt.Printf("%s", err.Error())
}
fmt.Printf("Name:%s\nType:%s\nProperties:%s\n", goJson.Name, goJson.Type, goJson.Properties)
//生成JSON串
properties := Properties{
Slice: "没有",
Array: "数组",
Interface: "接口",
Struct: "没有",
}
goJson1 := GoJson{
Name: "PHP",
Type: "Dynamic",
Properties: properties,
}
j, err := json.Marshal(goJson1)
if err != nil {
fmt.Println("%s", err.Error())
}
fmt.Println(string(j))
}