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语言标准库文档中文版
原文地址:https://www.cnblogs.com/fhb2011/p/8975184.html
时间: 2024-11-05 16:27:41