• go语言之进阶篇通过结构体生成json


    1、通过结构体生成json

    示例:

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    //成员变量名首字母必须大写
    type IT struct {
    	Company  string
    	Subjects []string
    	IsOk     bool
    	Price    float64
    }
    
    func main() {
    	//定义一个结构体变量,同时初始化
    	s := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666}
    
    	//编码,根据内容生成json文本
    	buf, err := json.Marshal(s)
    	if err != nil {
    		fmt.Println("err = ", err)
    		return
    	}
    	fmt.Println("buf = ", string(buf))
    }
    

    执行结果:

    buf =  {"Company":"itcast","Subjects":["Go","C++","Python","Test"],"IsOk":true,"Price":666.666}
    

      

    2、根据结构体生成json

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    //成员变量名首字母必须大写
    type IT struct {
    	Company  string
    	Subjects []string
    	IsOk     bool
    	Price    float64
    }
    
    func main() {
    	//定义一个结构体变量,同时初始化
    	s := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666}
    
    	//编码,根据内容生成json文本
    	buf, err := json.MarshalIndent(s, "", "	") //格式化编码
    	if err != nil {
    		fmt.Println("err = ", err)
    		return
    	}
    
    	fmt.Println("buf = ", string(buf))
    }
    

    执行结果:

    buf =  {
    	"Company": "itcast",
    	"Subjects": [
    		"Go",
    		"C++",
    		"Python",
    		"Test"
    	],
    	"IsOk": true,
    	"Price": 666.666
    }
    

      

     3、struct_tag的使用 (通过二次编码,可以把大写变成小写,还可以以字符串方式输出)

    示例: 

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    //成员变量名首字母必须大写
    type IT struct {
    	//Company  string   `json:"-"` //此字段不会输出到屏幕
    
    	//下面的写法都是二次编码,可以把大写变成小写
    	Company  string   `json:"company"`
    	Subjects []string `json:"subjects"`
    	IsOk     bool     `json:"isok"`
    	//转成字符串再输出编码
    	//IsOk  bool    `json:"string"`
    	Price float64 `json:"price"`
    }
    
    func main() {
    	//定义一个结构体变量,同时初始化
    	s := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666}
    
    	//编码,根据内容生成json文本
    	buf, err := json.MarshalIndent(s, "", " ") //格式化编码
    	if err != nil {
    		fmt.Println("err = ", err)
    		return
    	}
    
    	fmt.Println("buf = ", string(buf))
    }
    

    执行结果:

    buf =  {
     "company": "itcast",
     "subjects": [
      "Go",
      "C++",
      "Python",
      "Test"
     ],
     "isok": true,
     "price": 666.666
    }
    

      

  • 相关阅读:
    spring boot中 使用http请求
    spring boot 多层级mapper
    spring boot 使用拦截器,注解 实现 权限过滤
    spring boot 集成mybatis报错
    spring boot 使用拦截器 实现 用户登录拦截
    mac eclipse 删除不用的workspace
    maven+eclipse+mac+tomcat 多模块发布
    启动spring boot 异常
    安装 redis [standlone模式]
    quartz项目中的运用
  • 原文地址:https://www.cnblogs.com/nulige/p/10265713.html
Copyright © 2020-2023  润新知