no-image

golang json 编码解码

golang "encoding/json"包实现了json对象的编解码
https://www.cnblogs.com/fhb2011/p/8975184.html
一、编码

func Marshal(v interface{}) ([]byte, error)
Marshal函数使用下面的基于类型的默认编码格式:

布尔类型编码为json布尔类型。

浮点数、整数和Number类型的值编码为json数字类型。

字符串编码为json字符串。角括号"<"和">"会转义为"\u003c"和"\u003e"以避免某些浏览器吧json输出错误理解为HTML。基于同样的原因,"&"转义为"\u0026"。

数组和切片类型的值编码为json数组,但[]byte编码为base64编码字符串,nil切片编码为null。

结构体的值编码为json对象。每一个导出字段变成该对象的一个成员

Example:

package main

import(
    "fmt"
    "encoding/json"
)
func main() {
    type User struct{
        Name string
        Age int
    }
    user := User{
        Name:"tom",
        Age:3,
    }
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println("json Marshal fail:", err)
    }
    fmt.Println(string(b))
}

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 MARKDOWN_HASHab3cc8bd113dd144267d0dea32e61e15MARKDOWNHASH
}
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}