go json使用详解

导入

import "encoding/json"

json是go的标准库

Unmarshal

func Unmarshal(data []byte, v interface{}) error
Unmarshal函数解析json编码的数据并将结果存入v指向的值。
Bool                   对应JSON布尔类型
float64                对应JSON数字类型
string                 对应JSON字符串类型
[]interface{}          对应JSON数组
map[string]interface{} 对应JSON对象
nil                    对应JSON的null

Marshal

func Marshal(v interface{}) ([]byte, error)

Marshal函数返回v的json编码。

MarshalIndent

func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
MarshalIndent类似Marshal但会使用缩进将输出格式化。其可读性更高
package main 
import(
    "fmt"
    "encoding/json"
    "os"
)
type Address struct {
    City, State string
}
type Person struct {
    Id        int      `json:"id"` //id作为该JSON字段的key值
    FirstName string    //不设置标签则默认使用FirstName为字段key值
    LastName  string   `json:"-"` //字段被本包忽略,即使有值也不输出
    Age       int      `json:",omitempty"` //含omitempty选项的字段如果为空值会省略,如果存在Age作为该JSON字段的key值
    Height    float32  `json:"height,omitempty"` //含omitempty选项的字段如果为空值会省略,如果存在height作为该JSON字段的key值
    Address         //匿名字段(其标签无效)会被处理为其字段是外层结构体的字段,所以没有Address这个元素,而是直接显示City, State这两个元素
}

func main() {
    v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
    v.Address = Address{"Hanga Roa", "Easter Island"}
    output, err := json.MarshalIndent(v, "&", "    ")//每行以&作为前缀,并缩进四个空格
    if err != nil {
        fmt.Printf("error: %v\n", err)
    }
    os.Stdout.Write(output)
}

结果:
userdeMBP:go-learning user$ go run test.go
{
&    "id": 13,
&    "FirstName": "John",
&    "Age": 42,
&    "City": "Hanga Roa",
&    "State": "Easter Island"
&}

实例

package main
 
import (
    "encoding/json"
    "fmt"
    "os"
)
 
type ConfigStruct struct {
    Host              string   `json:"host"`
    Port              int      `json:"port"`
    AnalyticsFile     string   `json:"analytics_file"`
    StaticFileVersion int      `json:"static_file_version"`
    StaticDir         string   `json:"static_dir"`
    TemplatesDir      string   `json:"templates_dir"`
    SerTcpSocketHost  string   `json:"serTcpSocketHost"`
    SerTcpSocketPort  int      `json:"serTcpSocketPort"`
    Fruits            []string `json:"fruits"`
}
 
type Other struct {
    SerTcpSocketHost string   `json:"serTcpSocketHost"`
    SerTcpSocketPort int      `json:"serTcpSocketPort"`
    Fruits           []string `json:"fruits"`
}
 
func main() { 
    jsonStr := `{"host": "http://localhost:9090","port": 9090,"analytics_file": "","static_file_version": 1,"static_dir": "E:/Project/goTest/src/","templates_dir": "E:/Project/goTest/src/templates/","serTcpSocketHost": ":12340","serTcpSocketPort": 12340,"fruits": ["apple", "peach"]}`
 
    //json str 转map
    var dat map[string]interface{}
    if err := json.Unmarshal([]byte(jsonStr), &dat); err == nil {
        fmt.Println("==============json str 转map=======================")
        fmt.Println(dat)
        fmt.Println(dat["host"])
    }
 
    //json str 转struct
    var config ConfigStruct
    if err := json.Unmarshal([]byte(jsonStr), &config); err == nil {
        fmt.Println("================json str 转struct==")
        fmt.Println(config)
        fmt.Println(config.Host)
    }
 
    //json str 转struct(部份字段)
    var part Other
    if err := json.Unmarshal([]byte(jsonStr), &part); err == nil {
        fmt.Println("================json str 转struct==")
        fmt.Println(part)
        fmt.Println(part.SerTcpSocketPort)
    }
 
    //struct 到json str
    if b, err := json.Marshal(config); err == nil {
        fmt.Println("================struct 到json str==")
        fmt.Println(string(b))
    }
 
    //map 到json str
    fmt.Println("================map 到json str=====================")
    enc := json.NewEncoder(os.Stdout)
    enc.Encode(dat)
 
    //array 到 json str
    arr := []string{"hello", "apple", "python", "golang", "base", "peach", "pear"}
    lang, err := json.Marshal(arr)
    if err == nil {
        fmt.Println("================array 到 json str==")
        fmt.Println(string(lang))
    }
 
    //json 到 []string
    var wo []string
    if err := json.Unmarshal(lang, &wo); err == nil {
        fmt.Println("================json 到 []string==")
        fmt.Println(wo)
    }
}
# json  

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×