博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
33. golang中struct、json、map互相转化2
阅读量:5242 次
发布时间:2019-06-14

本文共 6933 字,大约阅读时间需要 23 分钟。

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=======================================================

转载于:https://www.cnblogs.com/fengchuiyizh/p/11564794.html

你可能感兴趣的文章
ef codefirst VS里修改数据表结构后更新到数据库
查看>>
boost 同步定时器
查看>>
[ROS] Chinese MOOC || Chapter-4.4 Action
查看>>
简单的数据库操作
查看>>
解决php -v查看到版本与phpinfo()版本不一致问题
查看>>
iOS-解决iOS8及以上设置applicationIconBadgeNumber报错的问题
查看>>
亡灵序曲-The Dawn
查看>>
Redmine
查看>>
帧的最小长度 CSMA/CD
查看>>
xib文件加载后设置frame无效问题
查看>>
编程算法 - 左旋转字符串 代码(C)
查看>>
IOS解析XML
查看>>
Python3多线程爬取meizitu的图片
查看>>
树状数组及其他特别简单的扩展
查看>>
zookeeper适用场景:分布式锁实现
查看>>
110104_LC-Display(液晶显示屏)
查看>>
全连接神经网络(DNN)
查看>>
httpd_Vhosts文件的配置
查看>>
php学习笔记
查看>>
普通求素数和线性筛素数
查看>>