1. 程式人生 > >golang json 編碼解碼

golang json 編碼解碼

實現 ron 北京 tput UC port 上海 XA 中文版

golang "encoding/json"包實現了json對象的編解碼

一、編碼

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

Marshal函數使用下面的基於類型的默認編碼格式:

布爾類型編碼為json布爾類型。

浮點數、整數和Number類型的值編碼為json數字類型。

字符串編碼為json字符串。角括號"<"和">"會轉義為"\u003c"和"\u003e"以避免某些瀏覽器吧json輸出錯誤理解為HTML。基於同樣的原因,"&"轉義為"\u0026"。

數組和切片類型的值編碼為json數組,但[]byte編碼為base64編碼字符串,nil切片編碼為null。

結構體的值編碼為json對象。每一個導出字段變成該對象的一個成員

Example:

 1 package main
 2 
 3 import(
 4     "fmt"
 5     "encoding/json"
 6 )
 7 func main() {
 8     type User struct{
 9         Name string
10         Age int
11     }
12     user := User{
13         Name:"tom",
14         Age:3,
15     }
16     b, err := json.Marshal(user)
17 if err != nil { 18 fmt.Println("json Marshal fail:", err) 19 } 20 fmt.Println(string(b)) 21 }

Output:

{"Name":"tom","Age":3}

1 不可導出字段,不會被編碼

Example:

type User struct{
        Name string
        age int
    }
    user := User{
        Name:"tom",
        age:3,
    }
    b, _ :
= json.Marshal(user) fmt.Println(string(b))

Output:

{"Name":"tom"}

2 可通過結構體標簽,改變編碼的json對象

Example:

type User struct{
        Name string `json:"name"`
        Age int     `json:"ageeeeeeeeeeeeeeeeee"`
    }
    user := User{
        Name:"tom",
        Age:3,
    }
    b, _ := json.Marshal(user)
    fmt.Println(string(b))

Output:

{"name":"tom","ageeeeeeeeeeeeeeeeee":3}

3 復雜結構體編碼:

   指針編碼為它指向的值

   切片編碼為數組

   結構體的值編碼為json對象

Example:

    // 復雜結構體編碼
    //基本類型指針,結構體指針,切片,切片指針,
    type Contact struct {
        Addr string
        Phone string
    }

    type User struct {
        Name string
        Age *int
        C1 *Contact
        C2 []Contact
        C3 []*Contact
    }
    age := 20
    c1 := Contact{"北京","12345"}
    cArr := [...]Contact{Contact{"北京","11111"},Contact{"深圳","22222"},Contact{"上海","33333"}}
    c2 := cArr[:2]
    c3 := make([]*Contact,0)
    c3 = append(c3, &cArr[0])
    c3 = append(c3, &cArr[1])

    user := User{
        Name:    "Tom",
        Age:     &age,
        C1:      &c1,
        C2:      c2,
        C3:      c3,
    }
    fmt.Printf("struct: %v\n", user)
    b, _ := json.Marshal(user)
    fmt.Println("json: ", string(b))

Output:

struct: {Tom 0xc04204a1c8 0xc042044580 [{北京 11111} {深圳 22222}] [0xc042086000 0xc042086020]}
json:  {"Name":"Tom","Age":20,"C1":{"Addr":"北京","Phone":"12345"},"C2":[{"Addr":"北京","Phone":"11111"},{"Addr":"深圳","Phone":"22222"}],"C3":[{"Addr":"北京","Phone":"11111"},{"Addr":"深圳","Phone":"22222"}]}

二、解碼

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

Example

//json解碼 測試
    type Contact struct {
        Addr string
        Phone string
    }

    type User struct {
        Name string
        Age *int
        C1 *Contact
        C2 []Contact
        C3 []*Contact
    }

    user := User{}
    j := `{
                "Name": "Tom",
                "Age": 20,
                "C1": {
                    "Addr": "北京",
                    "Phone": "12345"
                },
                "C2": [{
                    "Addr": "北京",
                    "Phone": "11111"
                }, {
                    "Addr": "深圳",
                    "Phone": "22222"
                }],
                "C3": [{
                    "Addr": "北京",
                    "Phone": "11111"
                }, {
                    "Addr": "深圳",
                    "Phone": "22222"
                }]
            }`
    err := json.Unmarshal([]byte(j), &user)
    if err != nil {
        fmt.Println("json Unmarshal fail!")
    }
    fmt.Printf("%v\n", user)
    fmt.Println(*user.Age)
    fmt.Println(*user.C1)
    fmt.Println(*user.C3[0])

Output

{Tom 0xc04204a3a8 0xc0420447a0 [{北京 11111} {深圳 22222}] [0xc042044860 0xc042044880]}
20
{北京 12345}
{北京 11111}

參考: Go語言標準庫文檔中文版

golang json 編碼解碼