在Web编程中,通常涉及数据传输序列化问题,json是一种常用的数据格式,在C语言中,有一个cjson的库可以解析/序列化/反序列化json格式的数据,在Go语言提供了原生的API函数来处理json数据
注意,在Go语言中,结构体变量大写代表public,小写代表private
package main
import (
"encoding/json"
"fmt"
)
type User struct {
UserName string
NickName string
Age int
Birthday string
Sex string
Phone string
}
func main() {
User1 := &User{
UserName: "user1",
NickName: "xieyang",
Age: 18,
Birthday: "2008/8/8",
Sex: "man",
Phone: "110",
}
data, err := json.Marshal(User1)
if err != nil {
fmt.Printf("json.marshal failed, err:", err)
return
}
fmt.Printf("%s\n", string(data))
}
下面的代码先将结构体序列化为字符串,再从字符串反序列回到结构体
package main
import (
"encoding/json"
"fmt"
)
type User struct {
UserName string
NickName string
Age int
Birthday string
Sex string
Phone string
}
func testStruct() (ret string, err error) {
User1 := &User{
UserName: "user1",
NickName: "xieyang",
Age: 18,
Birthday: "2008/8/8",
Sex: "man",
Phone: "110",
}
data, err := json.Marshal(User1)
if err != nil {
err = fmt.Errorf("json marshal failed,err:", err)
return
}
ret = string(data)
return
}
func test() {
data, err := testStruct()
if err != nil {
fmt.Println("test struct failed,", err)
return
}
var user1 User
err = json.Unmarshal([]byte(data), &user1)
if err != nil {
fmt.Println("test struct failed,", err)
return
}
fmt.Println(user1)
}
func main() {
test()
}