在golang中利用 工具包”encoding/json ” 实现编解码

 

json编码

函数 

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

定义结构体,编码,转换为[]byte格式

package main

import (
	"encoding/json"
	"fmt"
)

type Page struct {
	Code int    `json:"code"`
	Result interface{} `json:"result"`
}

func main()  {
	p := &Page{
		Result: "hello json",
		Code: 1,
	}
	jsonP,err := json.Marshal(p)
	if err != nil {
		fmt.Println("json err:", err)
	}
	fmt.Println(jsonP) //[]byte格式
	fmt.Println(string(jsonP))

}

 

 

json解码:

函数 

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

定义结构体,解码为struct格式

例子:

package main

import (
	"encoding/json"
	"fmt"
)

type Page struct {
	Code int    `json:"code"`
	Result interface{} `json:"result"`
}

func main()  {
	var p Page
	b := []byte(`{"result":"hello json","code":1}`)
	err := json.Unmarshal(b, &p)
	if err != nil {
	fmt.Println("json err:", err)
	}
	fmt.Println(p)
}

 

注意!!!:类属性如果是小写开头,则其序列化会丢失属性对应的值,同时也无法进行Json解析。因此结构体中的字段要大写开头!!!

只要是可导出成员(变量首字母大写),都可以转成json。因若小写则是不可导出的,故无法转成json

                    

 

 

参考链接:go 处理json