本文主要是介绍golang基础-json序列化、反序列化、自定义error,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
-
-
-
- json协议
- 结构体转json
- map转json
- int转json
- slice转json
- json反序列化为结构体
- json反序列化为map
- 自定义error
-
-
json协议
结构体转json
package mainimport ("fmt""encoding/json")type User struct {UserName string `json:"username"`NickName string `json:"nickname"`Age intBirthday stringSex stringEmail stringPhone string
}
/*结构体转json*/func testStruct() {user1 := &User{UserName: "user1",NickName: "上课看似",Age: 18,Birthday: "2008/8/8",Sex: "男",Email: "mahuateng@qq.com",Phone: "110",}data, err := json.Marshal(user1)if err != nil {fmt.Printf("json.marshal failed, err:", err)return}fmt.Printf("%s\n", string(data))
}func main() {testStruct()fmt.Println("----")
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
{"username":"user1","nickname":"上课看似","Age":18,"Birthday":"2008/8/8","Sex":"男","Email":"mahuateng@qq.com","Phone":"110"}
----
PS E:\golang\go_pro\src\safly>
map转json
package mainimport ("fmt""encoding/json")type User struct {UserName string `json:"username"`NickName string `json:"nickname"`Age intBirthday stringSex stringEmail stringPhone string
}
/*map转json*/func testMap() {var mmp map[string]interface{}mmp = make(map[string]interface{})mmp["username"] = "user"mmp["age"] = 19mmp["sex"] = "man"data,err := json.Marshal(mmp)if err != nil{fmt.Println("json marshal failed,err:",err)return}fmt.Println("%s\n",string(data))
}func main() {testMap()fmt.Println("----")
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
{"age":19,"sex":"man","username":"user"}
----
PS E:\golang\go_pro\src\safly>
int转json
package mainimport ("fmt""encoding/json")type User struct {UserName string `json:"username"`NickName string `json:"nickname"`Age intBirthday stringSex stringEmail stringPhone string
}
/*slice转json*/func testSlice() {}func testInt() {var age = 100data, err := json.Marshal(age)if err != nil {fmt.Printf("json.marshal failed, err:", err)return}fmt.Printf("%s\n", string(data))
}func main() {testSlice()testInt()fmt.Println("----")
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
100
----
PS E:\golang\go_pro\src\safly>
slice转json
package mainimport ("fmt""encoding/json")func testSlice() {var m map[string]interface{}var s []map[string]interface{}m = make(map[string]interface{})m["username"] = "user1"m["age"] = 18m["sex"] = "man"s = append(s, m)m = make(map[string]interface{})m["username"] = "user2"m["age"] = 29m["sex"] = "female"s = append(s, m)data, err := json.Marshal(s)if err != nil {fmt.Printf("json.marshal failed, err:", err)return}fmt.Printf("%s\n", string(data))
}func main() {testSlice()}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
[{"age":18,"sex":"man","username":"user1"},{"age":29,"sex":"female","username":"user2"}]
PS E:\golang\go_pro\src\safly>
json反序列化为结构体
package mainimport ("encoding/json""fmt"
)type User struct {UserName string `json:"username"`NickName string `json:"nickname"`Age intBirthday stringSex stringEmail stringPhone string
}func testStruct() (ret string, err error) {user1 := &User{UserName: "user1",NickName: "上课看似",Age: 18,Birthday: "2008/8/8",Sex: "男",Email: "mahuateng@qq.com",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 Usererr = json.Unmarshal([]byte(data), &user1)if err != nil {fmt.Println("Unmarshal failed, ", err)return}fmt.Println(user1)
}func main() {test()// test2()
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
{user1 上课看似 18 2008/8/8 男 mahuateng@qq.com 110}
PS E:\golang\go_pro\src\safly>
json反序列化为map
package mainimport ("encoding/json""fmt"
)func testMap() (ret string, err error) {var m map[string]interface{}m = make(map[string]interface{})m["username"] = "user1"m["age"] = 18m["sex"] = "man"data, err := json.Marshal(m)if err != nil {err = fmt.Errorf("json.marshal failed, err:", err)return}ret = string(data)return
}func test2() {data, err := testMap()if err != nil {fmt.Println("test map failed, ", err)return}var m map[string]interface{}err = json.Unmarshal([]byte(data), &m)if err != nil {fmt.Println("Unmarshal failed, ", err)return}fmt.Println(m)
}func main() {test2()
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
map[age:18 sex:man username:user1]
PS E:\golang\go_pro\src\safly>
自定义error
package mainimport ("fmt""os""time"
)type PathError struct {path stringop stringcreateTime stringmessage string
}func (p *PathError) Error() string {return fmt.Sprintf("path=%s op=%s createTime=%s message=%s", p.path,p.op, p.createTime, p.message)
}
/*
type error interface {Error() string
}
*/
func Open(filename string) error {file, err := os.Open(filename)if err != nil {return &PathError{path: filename,op: "read",message: err.Error(),createTime: fmt.Sprintf("%v", time.Now()),}}defer file.Close()return nil
}func main() {err := Open("C:/sdklflakfljdsafjs.txt")switch v := err.(type) {case *PathError:fmt.Println("get path error,", v)default:}}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
get path error, path=C:/sdklflakfljdsafjs.txt op=read createTime=2017-11-05 20:09:23.4928719 +0800 CST message=open C:/sdklflakfljdsafjs.txt: The system cannot find the file specified.
PS E:\golang\go_pro\src\safly>
这篇关于golang基础-json序列化、反序列化、自定义error的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!