zoukankan      html  css  js  c++  java
  • Golang操作结构体、Map转化为JSON

    结构体生成Json

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type IT struct {
        Company string `json:"-"` //此字段不会输出到屏幕
        //Company  string   `json:"company"`       这样打印输出别名首字母就会小写(二次编码)
        Subjects []string `json:"subjects"` //二次编码
        IsOk     bool     `json:",string"`
        Price    float64  `json:",string"`
    }
    
    func main() {
        //定义一个结构体变量,同时初始化
        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 =  {
            "subjects": [   //首字母小写
                   "Golang",
                    "PHP",
                    "Java",
                    "C++"
            ],
           "IsOk": "true",   //string类型
           "Price": "666.666"
    }
    

      Json转成结构体

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type IT struct {
        Address   string   `json:"address"`
        Languages []string `json:"languages"` //二次编码
        Status    bool     `json:"isok"`
        Price     float64  `json:"price"`
    }
    
    func main() {
    
        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
    ", tmp)
    
        type IT2 struct {
            Subjects []string `json:"languages"` //二次编码
        }
    
        var tmp2 IT2
        err = json.Unmarshal([]byte(jsonBuf), &tmp2) //第二个参数要地址传递
        if err != nil {
            fmt.Println("err = ", err)
            return
        }
        fmt.Printf("tmp2 = %+v
    ", tmp2)
    
    }
    

      

    tmp = {Address:北京 Languages:[Golang PHP Java Python] Status:false Price:666.666}
    tmp2 = {Subjects:[Golang PHP Java Python]}
    

      Map生成Json

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        //创建一个map
        m := make(map[string]interface{}, 4) //因为类型多,可以用interface空接口
        m["address"] = "北京"
        m["languages"] = []string{"Golang", "PHP", "Java", "Python"}
        m["status"] = true
        m["price"] = 666.666
    
        //编码成json
        //result, err := json.Marshal(m)
        //result =  {"address":"北京","languages":["Golang","PHP","Java","Python"],"price":666.666,"status":true}
        result, err := json.MarshalIndent(m, "", "    ")
        if err != nil {
            fmt.Println("err = ", err)
            return
        }
        fmt.Println("result = ", string(result))
    }
    

      

    result =  {
            "address": "北京",
            "languages": [
                    "Golang",
                    "PHP",
                    "Java",
                    "Python"
            ],
            "price": 666.666,
            "status": true
    }
    

      Json转化为Map

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        jsonBuf := `
        {
        "company": "itcast",
        "subjects": [
            "Go",
            "C++",
            "Python",
            "Test"
        ],
        "isok": true,
        "price": 666.666
    }`
    
        //创建一个map
        m := make(map[string]interface{}, 4)
    
        err := json.Unmarshal([]byte(jsonBuf), &m) //第二个参数要地址传递
        if err != nil {
            fmt.Println("err = ", err)
            return
        }
        fmt.Printf("m = %+v
    ", m)
    
        //    var str string
        //    str = string(m["company"]) //err, 无法转换
        //    fmt.Println("str = ", str)
    
        var str string
    
        //类型断言, 值,它是value类型
        for key, value := range m {
            //fmt.Printf("%v ============> %v
    ", key, value)
            switch data := value.(type) {
            case string:
                str = data
                fmt.Printf("map[%s]的值类型为string, value = %s
    ", key, str)
            case bool:
                fmt.Printf("map[%s]的值类型为bool, value = %v
    ", key, data)
            case float64:
                fmt.Printf("map[%s]的值类型为float64, value = %f
    ", key, data)
            case []string:
                fmt.Printf("map[%s]的值类型为[]string, value = %v
    ", key, data)
            case []interface{}:
                fmt.Printf("map[%s]的值类型为[]interface, value = %v
    ", key, data)
            }
    
        }
    
    }
    

      

    map[address]的值类型为string, value = 北京
    map[Languages]的值类型为[]interface, value = [Golang PHP Java Python]
    map[Status]的值类型为bool, value = true
    map[price]的值类型为float64, value = 666.666000
    

      []interface{}转json

    package main
     
    import (
        "encoding/json"
        "fmt"
    )
    func main(){
    	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))
    }
    

      

    result =  [
        5,
        [
            "Golang",
            "PHP",
            "Java",
            "Python"
        ],
        {
            "hello": "world"
        }
    ]
    

      

  • 相关阅读:
    Linux-C基础知识学习:C语言作业-输入三角形底和高,输出三角形面积
    Linux-C基础知识学习:C语言作业-从键盘输入一个三位数,以逆序输出。例如输入456,输出654
    Linux基础知识学习:Linux下修改文件名或修改文件夹名称(有待解决问题)
    Linux基础知识学习:linux用命令重启
    Linux基础知识学习:linux用命令重启
    Linux基础知识学习:Linux中修改环境变量及使环境变量生效的方法
    Linux基础知识学习:Linux中修改环境变量及使环境变量生效的方法
    Linux基础知识学习:安装JDK出现 cannot execute binary file
    Linux基础知识学习:安装JDK(tar.gz)
    Linux基础知识学习:查看所使用的Linux系统是32位还是64 位的方法
  • 原文地址:https://www.cnblogs.com/navysummer/p/10996570.html
Copyright © 2011-2022 走看看