go-json类

package main

import (
    "encoding/json"
    "fmt"
)

/*
{
    "company":"itcast"
    "":[
        "go"
        "c++"
    ],
    "isok":"ok"
    "price":"666"
}
*/
//成员变量名首字母必须大写
type IT struct {
    Company string `json:"company"` //变为小写
    Subject []string
    Isok    bool `json:",string"`
    Price   float32
}

type IT2 struct {
    Company string   `json:"company"`
    Subject []string `json:"subject"`
    Isok    bool     `json:"isok"`
    Price   float32  `json:"price"`
}

func main() {
    s := IT{"itcast", []string{"go", "c++"}, true, 666}

    buf, err := json.Marshal(s)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(string(buf))
    //{"Company":"itcast","Subject":["go","c++"],"Isok":true,"Price":666}

    //格式化编码
    buf2, err := json.MarshalIndent(s, "", " ")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(buf2))

    //通过Map生成json
    m := make(map[string]interface{}, 4)
    m["compary"] = "itcast"
    m["subjects"] = []string{"go", "c++"}
    m["Isok"] = true
    m["price"] = 777

    result, err2 := json.Marshal(m)
    if err2 != nil {
        return
    }
    fmt.Println(string(result))

    //json 解析到 结构体
    jsonbuf := `{"Isok":true,"compary":"itcast","price":777,"subjects":["go","c++"]}`

    var tmp IT2
    err3 := json.Unmarshal([]byte(jsonbuf), &tmp)
    if err3 != nil {
        fmt.Println(err3)
        return
    }
    fmt.Println(tmp)

    //json 解析到map
    m2 := make(map[string]interface{}, 4)
    err4 := json.Unmarshal([]byte(jsonbuf), &m2)
    if err4 != nil {
        fmt.Println(err4)
    }
    fmt.Println("map = ", m2)

    //取元素
    for key, value := range m {
        fmt.Println(key, value)
        switch data := value.(type) {
        case string:
            fmt.Println(data)
        case int:
            fmt.Println(data)
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/osbreak/p/10508096.html