GO 语言中的`` 语法

`` 语法 理解为不转译字符串的意思,可以json yaml 等一起使用。

选择的控制字段有三种

  1. -:不要解析这个字段
  2. omitempty:当字段为空(默认值)时,不要解析这个字段。比如 false、0、nil、长度为 0 的 array,map,slice,string
  3. FieldName:当解析 json 的时候,使用这个名字

1、struct && json

package main

import (
    "encoding/json"
    "fmt"
)

type Student struct {
    StudentId      string `json:"sid"`
    StudentName    string `json:"sname"`
    StudentClass   string `json:"class"`
    StudentTeacher string `json:"teacher"`
}

type StudentNoJson struct {
    StudentId      string
    StudentName    string
    StudentClass   string
    StudentTeacher string
}

type StudentWithOption struct {
StudentId      string //默认使用原定义中的值
StudentName    string `json:"sname"`// 解析(encode/decode) 的时候,使用 `sname`,而不是 `Field`
StudentClass   string `json:"class,omitempty"`// 解析的时候使用 `class`,如果值为空,就忽略它
StudentTeacher string `json:"-"`// 解析的时候忽略该字段。默认情况下会解析这个字段,因为它是大写字母开头
}

func main() {
    //NO.1 with json struct tag
    s := &Student{StudentId: "1", StudentName: "fengxm", StudentClass: "0903", StudentTeacher: "feng"}
    jsonString, _ := json.Marshal(s)

    fmt.Println(string(jsonString))
    //{"sid":"1","sname":"fengxm","class":"0903","teacher":"feng"}
    newStudent := new(Student)
    json.Unmarshal(jsonString, newStudent)
    fmt.Println(newStudent)
    //&{1 fengxm 0903 feng}
    //Unmarshal 是怎么找到结构体中对应的值呢?比如给定一个 JSON key Filed,它是这样查找的:
    // 首先查找 tag 名字(关于 JSON tag 的解释参看下一节)为 Field 的字段
    // 然后查找名字为 Field 的字段
    // 最后再找名字为 FiElD 等大小写不敏感的匹配字段。
    // 如果都没有找到,就直接忽略这个 key,也不会报错。这对于要从众多数据中只选择部分来使用非常方便。

    //NO.2 without json struct tag
    so := &StudentNoJson{StudentId: "1", StudentName: "fengxm", StudentClass: "0903", StudentTeacher: "feng"}
    jsonStringO, _ := json.Marshal(so)

    fmt.Println(string(jsonStringO))
    //{"StudentId":"1","StudentName":"fengxm","StudentClass":"0903","StudentTeacher":"feng"}

    //NO.3 StudentWithOption
    studentWO := new(StudentWithOption)
    js, _ := json.Marshal(studentWO)

    fmt.Println(string(js))
    //{"StudentId":"","sname":""}

    studentWO2 := &StudentWithOption{StudentId: "1", StudentName: "fengxm", StudentClass: "0903", StudentTeacher: "feng"}
    js2, _ := json.Marshal(studentWO2)

    fmt.Println(string(js2))
    //{"StudentId":"1","sname":"fengxm","class":"0903"}
}

2、struct && yaml

/*
* Copyright(C),2019-2020, email: zsf5110@163.com
* Author:  zhangfeng
* Version: 1.0.0
* Date:    6/3/20 9:44 PM
* Description:
*
 */
package main

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
	"path/filepath"
)

func main() {
	execpath := filepath.Dir(os.Args[0])
	fmt.Println(execpath)

	fmt.Println("StudentsInfo test")
	studentsInfo := StudentsInfo{Id: "110"}
	str1, err := yaml.Marshal(&studentsInfo)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(str1))
	ioutil.WriteFile(execpath + "/test.yaml", str1, os.ModeType)

	str2,_ := ioutil.ReadFile(execpath + "/test.yaml")
	studentsInfo2 := new(StudentsInfo)
	yaml.Unmarshal(str2, studentsInfo2)
	fmt.Println(*studentsInfo2)

	fmt.Println("\nStudentsInfoWith test")
	studentsInfoWith := StudentsInfoWith{Id: "112"}
	str3, _ := yaml.Marshal(&studentsInfoWith)
	fmt.Println(string(str3))
	studentsInfoWith2 := new(StudentsInfoWith)
	yaml.Unmarshal(str3, studentsInfoWith2)
	fmt.Println(*studentsInfoWith2)

	fmt.Println("\nStudentsInfoWithOption test")
	studentsInfoWithOption := StudentsInfoWithOption{Id: "113", Name: "zhang"}
	str4, _ := yaml.Marshal(studentsInfoWithOption)
	fmt.Println(string(str4))
}

type StudentsInfo struct {  // yaml 默认 全部首字符小写
	Id string
	Name string
	Age int
	Status bool
}

type StudentsInfoWith struct {  // 首先使用 `yaml:"id"`中的内容
	Id string  `yaml:"id"`
	Name string `yaml:"Name"`
	Age int `yaml:"age"`
	Status bool `yaml:"status"`
}

type StudentsInfoWithOption struct {
	Id string  `yaml:"id"`   // 使用 id
	Name string `yaml:"name,omitempty"` // 非空没有该字段
	Age int `yaml:"age,omitempty"`
	Status bool `yaml:"-"`   // 不管是不是 空 都没有该字段
}

输出内容

StudentsInfo test
id: "110"
name: ""
age: 0
status: false

{110  0 false}

StudentsInfoWith test
id: "112"
Name: ""
age: 0
status: false

{112  0 false}

StudentsInfoWithOption test
id: "113"
name: zhang

3、struct && json && yaml

/*
* Copyright(C),2019-2020, email: zsf5110@163.com
* Author:  zhangfeng
* Version: 1.0.0
* Date:    6/3/20 9:44 PM
* Description:
*
 */
package main

import (
	"encoding/json"
	"fmt"
	"gopkg.in/yaml.v2"
)

func main() {
	//YamlTest()
	fmt.Println("json")
	info := Info{Id: "110", Age: 15}
	jsonstr,_ := json.Marshal(&info)
	fmt.Println(string(jsonstr))


	fmt.Println("\nyaml")
	yamlstr,_ := yaml.Marshal(&info)
	fmt.Println(string(yamlstr))
}

type Info struct {
	Id string `json:"id" yaml:"id"`
	Name string
	Age int `json:"age" yaml:"age,omitempty"`
	Num string `json:"num,omitempty" yaml:"-"`
}

输出

json
{"id":"110","Name":"","age":15}

yaml
id: "110"
name: ""
age: 15

注意:第一部分参考网络资源,重复请联系更改。

  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值