package main import ( "database/sql" "encoding/json" "fmt" "github.com/gogf/gf/encoding/gjson" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/os/glog" "reflect" ) func main() { //JsonToStructDemo() } func db_to_json(){ // 数据库数据转成json字符串输出 db := g.DB("local") r, err:= db.Table("data_all").Where("name=?", "ad1909").One() fmt.Println(sql.ErrNoRows) if err != nil && err == sql.ErrNoRows { err = nil } //字符串数据转json对象 mjson,_ :=json.Marshal(r) mString :=string(mjson) fmt.Println(mString) if k, err := gjson.DecodeToJson([]byte(mString)); err != nil { glog.Error(err) } else { fmt.Println(k.Get("name")) } } // json 转其他格式 func jsonstr_to_other(){ data := `{ "users" : { "count" : 100, "list" : [ {"name" : "小明", "score" : 60}, {"name" : "John", "score" : 99.5} ] } }` if j, err := gjson.DecodeToJson([]byte(data)); err != nil { glog.Error(err) } else { //==========转json 字符串============================ c, _ := j.ToJson() fmt.Println("JSON:") fmt.Println(string(c)) fmt.Println("======================") fmt.Println("XML:") c, _ = j.ToXmlIndent() fmt.Println(string(c)) fmt.Println("======================") fmt.Println("YAML:") c, _ = j.ToYaml() fmt.Println(string(c)) fmt.Println("======================") fmt.Println("TOML:") c, _ = j.ToToml() fmt.Println(string(c)) } } // 遍历json func json_bianli(){ data := `{ "users" : { "count" : 100, "list" : [ {"name" : "小明", "score" : 60}, {"name" : "John", "score" : 99.5} ] } }` if j, err := gjson.DecodeToJson([]byte(data)); err != nil { glog.Error(err) } else { //=========================解析成json 两种方法================= //=============方法1================================== for _, v := range j.GetArray("users.list") { fmt.Println(v.(map[string]interface{})["name"]) //需要强转 } //=============方法2================================== for _, v := range j.GetJsons("users.list") { fmt.Println(v.Get("name")) //直接解析 } fmt.Println("John Score:", j.GetFloat32("users.list.1.score")) fmt.Println("John Score:", j.GetInt("users.count")) } } //=========================================(JSON <--->map) ======================================================= /* map =======> JSON字符串 */ //例子1 func Map_To_Json_1(){ m :=map[string]string{ "type":"10","msg":"hello."} mjson,_ :=json.Marshal(m) mString :=string(mjson) fmt.Printf("print mString:%s",mString) } //例子2 func Map_To_Json_2(){ mapInstances := []map[string]interface{}{} instance_1 := map[string]interface{}{ "name": "John", "age": 10} instance_2 := map[string]interface{}{ "name": "Alex", "age": 12} mapInstances = append(mapInstances, instance_1, instance_2) jsonStr, err := json.Marshal(mapInstances) if err != nil { fmt.Println("MapToJsonDemo err: ", err) } fmt.Println(string(jsonStr)) } /* JSON字符串 =======> map */ //例子1 func JsonToMapDemo() { jsonStr := `{"name": "jqw","age": 18}` var mapResult map[string]interface{} err := json.Unmarshal([]byte(jsonStr), &mapResult) if err != nil { fmt.Println("JsonToMapDemo err: ", err) } fmt.Println(mapResult) } //=========================================(JSON <--->map) ======================================================= //=========================================(JSON <--->结构体) ======================================================= type IT struct { Address string `json:"address"` Languages []string `json:"languages"` //二次编码 Status bool `json:"isok"` Price float64 `json:"price"` } /* JSON=======>结构体 */ //例子1 func Json_to_Struct(){ jsonBuf := ` { "address": "北京", "languages": [ "Golang", "PHP", "Java", "Python" ], "status": true, "price": 666.666 }` var tmp IT //定义一个结构体变量 err := json.Unmarshal([]byte(jsonBuf), &tmp) //第二个参数要地址传递 if err != nil { fmt.Println("err = ", err) return } fmt.Println("tmp = ", tmp) fmt.Printf("tmp = %+v\n", tmp) /* tmp = {北京 [Golang PHP Java Python] false 666.666} tmp = {Address:北京 Languages:[Golang PHP Java Python] Status:false Price:666.666} */ } //例子2 使用别名 type People struct { Name string `json:"name_title"` Age int `json:"age_size"` } func JsonToStructDemo(){ jsonStr := ` { "name_title": "jqw", "age_size":12 }` var people People err:=json.Unmarshal([]byte(jsonStr), &people) if err != nil { fmt.Println("err = ", err) return } fmt.Println(people) fmt.Printf("tmp = %+v\n", people) } /* 结构体=======>JSON */ // 例子1 func Struct_To_Json() { //定义一个结构体变量,同时初始化 s := IT{ "itcast", []string{ "Golang", "PHP", "Java", "C++"}, true, 666.666} //编码,根据内容生成json文本 //buf, err := json.Marshal(s) //buf = {"subjects":["Golang","PHP","Java","C++"],"IsOk":"true","Price":"666.666"} buf, err := json.MarshalIndent(s, "", " ") //格式化编码 if err != nil { fmt.Println("err = ", err) return } fmt.Println("buf = ", string(buf)) /* buf = { "address": "itcast", "languages": [ "Golang", "PHP", "Java", "C++" ], "isok": true, "price": 666.666 } */ } //=========================================(JSON <--->结构体) ======================================================== //=========================================[]interface{}转json ======================================================= func interface_to_json(){ var s []interface{} s = append(s,5) s = append(s,[]string{ "Golang", "PHP", "Java", "Python"}) s = append(s,map[string]string{ "hello":"world"}) result, err := json.MarshalIndent(s, "", " ") if err != nil { fmt.Println("err = ", err) return } fmt.Println("result = ", string(result)) } //=========================================[]interface{}转json ======================================================= //=========================================struct=>map======================================================= //需要安装一个第三方库 //在命令行中运行: go get github.com/goinggo/mapstructure func Map2Struct() { mapInstances := make(map[string]interface{}) mapInstances["Name"] = "amy" mapInstances["ID"] = 7 mapInstances["Age"] = 18 var account Account err := mapstructure.Decode(mapInstances, &account) if err != nil { fmt.Println(err) } fmt.Println(account) } func Struct2Map() { account := Account{ Name: "amy", ID: 007, Age: 18, } obj1 := reflect.TypeOf(account) obj2 := reflect.ValueOf(account) var data = make(map[string]interface{}) for i := 0; i < obj1.NumField(); i++ { data[obj1.Field(i).Name] = obj2.Field(i).Interface() } fmt.Println(data) } //=========================================struct=>map=======================================================