golang基础-json序列化、反序列化、自定义error

前端之家收集整理的这篇文章主要介绍了golang基础-json序列化、反序列化、自定义error前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

json协议

结构体转json

package main

import (

    "fmt"
    "encoding/json"

)

type User struct {
    UserName string `json:"username"`
    NickName string `json:"nickname"`
    Age      int
    Birthday string
    Sex      string
    Email    string
    Phone    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 main

import (

    "fmt"
    "encoding/json"

)

type User struct {
    UserName string `json:"username"`
    NickName string `json:"nickname"`
    Age      int
    Birthday string
    Sex      string
    Email    string
    Phone    string
}
/*map转json*/

func testMap() {
    var mmp  map[string]interface{}
    mmp = make(map[string]interface{})

    mmp["username"] = "user"
    mmp["age"] = 19
    mmp["sex"] = "man"

    data,err := json.Marshal(mmp)
    if err != nil{
        fmt.Println("json marshal Failed,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 main

import (

    "fmt"
    "encoding/json"

)

type User struct {
    UserName string `json:"username"`
    NickName string `json:"nickname"`
    Age      int
    Birthday string
    Sex      string
    Email    string
    Phone    string
}
/*slice转json*/

func testSlice() {

}


func testInt() {
    var age = 100
    data,err := json.Marshal(age)
    if err != nil {
        fmt.Printf("json.marshal Failed,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 main

import (

    "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"] = 18
    m["sex"] = "man"

    s = append(s,m)

    m = make(map[string]interface{})
    m["username"] = "user2"
    m["age"] = 29
    m["sex"] = "female"
    s = append(s,m)

    data,err := json.Marshal(s)
    if err != nil {
        fmt.Printf("json.marshal Failed,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 main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    UserName string `json:"username"`
    NickName string `json:"nickname"`
    Age      int
    Birthday string
    Sex      string
    Email    string
    Phone    string
}

func testStruct() (ret string,err error) {
    user1 := &User{
        UserName: "user1",err := json.Marshal(user1)
    if err != nil {
        err = fmt.Errorf("json.marshal Failed,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("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 main

import (
    "encoding/json"
    "fmt"
)


func testMap() (ret string,err error) {
    var m map[string]interface{}
    m = make(map[string]interface{})
    m["username"] = "user1"
    m["age"] = 18
    m["sex"] = "man"

    data,err := json.Marshal(m)
    if err != nil {
        err = fmt.Errorf("json.marshal Failed,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)
}



f

unc 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 main

import (
    "fmt"
    "os"
    "time"
)

type PathError struct {
    path       string
    op         string
    createTime string
    message    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>
原文链接:https://www.f2er.com/go/187747.html

猜你在找的Go相关文章