简介
Json(Javascript Object Nanotation)是一种数据交换格式,常用于前后端数据传输。任意一端将数据转换成json 字符串,
另一端再将该字符串解析成相应的数据结构,如string类型,strcut对象等。
go语言本身为我们提供了json的工具包”encoding/json”。
- Encoding
func Marshal(v interface{}) ([]byte, error)
递归进行json编码
func MarshalIndent(v interface{}, prefix, index string) ([]byte, error)
Marshallndent类似Marshal但会使用缩进将输出格式化。
- Decoding
func Unmarshal(data []byte, v interface{}) error
json解码
- type Decoder struct
func NewDecoder(r io.Reader) Decoder
NewDecoder创建一个从r读取并解码json对象的Decoder,解码器有自己的缓冲,并可能超前读取部分json数据。
func (dec *Decoder) UseNumber()
UseNumber方法将dec设置为当接收端是Interface{}接口时将json数字解码为Number类型而不是float64类型。
func (dec *Decoder) Decode(v interface{}) error
Decode从输入流读取下一个json编码值并保持在v指向的值里。
- type Encoder struct
func NewEncoder(w io.Writer) Encoder
NewEncoder创建一个将数据写入w的Encoder。
func (enc *Encoder) Encode(v interface{}) error
Encode将v的json编码写入输出流,并会写入一个换行符。
实例 1 序列化
结构体转换成json串
package main
import (
"fmt"
"encoding/json"
)
type User struct {
UserName string `json:"username"`
NickName string `json:"nick-name"`
Age int
Birthday string
Sex string
Email string
Phone string
}
func structTojson() {
u1 := &User {
UserName:"zhangsan",
NickName:"crize man",
Age:18,
Birthday:"1955/5/5",
Sex: "男",
Email: "zhangsan@qq.com",
Phone: "086 133 5555 5555",
}
data, err := json.Marshal(u1)
if err != nil {
fmt.Printf("json.marshal failed,err", err)
return
}
fmt.Printf("json:%s\n",string(data))
}
func main() {
structTojson()
fmt.Printf("--end---\n")
}
~/gomod/src/json$ go run structTojson.go
json:{"username":"zhangsan","nick-name":"crize man","Age":18,"Birthday":"1955/5/5","Sex":"男","Email":"zhangsan@qq.com","Phone":"086 133 5555 5555"}
--end---
实例 2 反序列化
package main
import (
"fmt"
"encoding/json"
)
type User struct {
UserName string `json:"username"`
NickName string `json:"nick-name"`
Age int
Birthday string
Sex string
Email string
Phone string
}
func structTojson() (res string, err error){
u1 := &User {
UserName:"zhangsan",
NickName:"crize man",
Age:18,
Birthday:"1955/5/5",
Sex: "男",
Email: "zhangsan@qq.com",
Phone: "086 133 5555 5555",
}
data, err := json.Marshal(u1)
if err != nil {
err = fmt.Errorf("json.marshal failed,err", err)
return
}
fmt.Printf("json:%s\n",string(data))
res = string(data)
return
}
func reSerial() {
data,err := structTojson()
if err != nil {
fmt.Println("reSerial failed",err)
return
}
var u1 User
err = json.Unmarshal([]byte(data),&u1)
if err != nil {
fmt.Println("unmarshal err:",err)
return
}
fmt.Printf("\n\r")
fmt.Println("unmarshal result:",u1)
}
func main() {
reSerial()
fmt.Printf("--end---\n")
}
- 运行结果
robot@ubuntu:~/gomod/src/json$ go run structTojson.go
json:{"username":"zhangsan","nick-name":"crize man","Age":18,"Birthday":"1955/5/5","Sex":"男","Email":"zhangsan@qq.com","Phone":"086 133 5555 5555"}
unmarshal result: {zhangsan crize man 18 1955/5/5 男 zhangsan@qq.com 086 133 5555 5555}
--end---
实例 3
package main
import (
"fmt"
"encoding/json"
)
func testSlice() {
var mp map[string]interface{}
var sl []map[string]interface{}
mp = make(map[string]interface{})
mp["name"] = "zhangfei"
mp["age"] = 18
mp["sex"] = "man"
sl = append(sl,mp)
fmt.Println("sl1:",sl)
mp = make(map[string]interface{}) //clear m value
mp["name"] = "guanyu"
mp["age"] = 19
mp["sex"] = "female"
sl = append(sl,mp)
fmt.Println("sl2:",sl)
mp = make(map[string]interface{}) //clear m value
mp["name"] = "liubei"
mp["age"] = 20
mp["sex"] = "female"
sl = append(sl,mp)
fmt.Println("sl3:",sl)
data,err := json.Marshal(sl)
if err != nil {
fmt.Printf("marshal failed ,err:",err)
return
}
fmt.Printf("res:%s\n",string(data))
}
func main() {
testSlice()
}