golang 和 json 字符串互转的问题

1. 说明

仅做了粗略的测试,不保证严谨性,但足以体现效果。

2. 测试

type T struct {
    Field1 string `json:"tEst1"` // test json tag
    FiEld2 string `bson:"test2"` // test non-json tag
    Field3 string `json:"teSt3"` // test ignore json tag
    Field4 string // test mismatched field
    field5 string // test not export
}

testJson := "{\"test1\": \"test json tag\", \"fIeLd2\": \"test non-json tag and ignore case\", \"Field3\":\"test ignore json tag\", \"Field\":\"test mismatched field\", \"field5\":\"test not export\"}"

bytes := []byte(testJson)
testT := T{}
err := json.Unmarshal(bytes, &testT)
if err != nil {
    fmt.Println("err:", err)
}
// 打印输出,有 json tag 的按照 json tag 比较,无 json tag 的按照字段名比较,比较不区分大小写,为导出字段和未匹配通过的字段忽略
fmt.Printf("%++v\n", testT) // {Field1:test json tag FiEld2:test non-json tag and ignore case Field3: Field4: field5:}

testT = T{
    Field1: "test field use tag",
    FiEld2: "test non-json tag",
    Field3: "test field use tag",
    Field4: "test no tag",
    field5: "test not export",
}
str, err := json.Marshal(testT)
// 输出转换的 json 字符串无未导出字段,无 tag 和非 json tag 字段使用字段名
fmt.Println(string(str)) // {"tEst1":"test field use tag","FiEld2":"test non-json tag","teSt3":"test field use tag","Field4":"test no tag"}

3. 结论

  • 不区分大小写
    golang 结构体(以下简称 struct)字段名称、struct tag(以下简称 tag)、和 json 字符串(以下简称 json)中的字段名之间不区分大小写,互相转换时,会优先检测是否存在 json 的 tag(且仅限于 json 的 tag),如果存在则优先和 tag 比较,未导出字段不参与转换。

    • struct -> json
      生成的字符串会优先使用 tag 作字段名,否则使用 struct 的字段名。
    • json -> struct
      json 字符串会优先按 json 的 tag 进行不区分大小写的匹配,如果匹配失败则忽略该字段;如果没有 json tag,则会按 struct 的字段名进行不区分大小写的匹配。
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容