Golang 中 反引号 Unmarshal 和 json 中的 omitempty 字段类型

package main

import (
    "encoding/json"
    "fmt"
)

//定义一个类型
type test struct {
    Name string `json:"name,omitempty"`
    Age  int    `json:"age,omitempty"`
}

func main() {
    t := test{}
    //testJson := `{"name":"zhao", "age": 1}`
    testJson := `{"age": 1}`
    _ = json.Unmarshal([]byte(testJson), &t)

    fmt.Println(fmt.Sprintf("%+v", t))
  // omitempty 字段类型为 在定义 给结构体 赋值的时候 如果没有 给此字段赋值 则不展示
    t1 := test{
        Name: "xin",
    }
    t1Data, _ := json.Marshal(t1)
    fmt.Println(string(t1Data))
}

>>>

{Name: Age:1}
{"name":"xin"}

 
邮箱: 1090055252@qq.com
原文地址:https://www.cnblogs.com/zhaoxianxin/p/14317685.html