GO json.Unmarshal() 解析不区分json字段的大小写

GO json.Unmarshal() 解析不区分json字段的大小写


demo


package main

import (
	"encoding/json"
	"fmt"
)

type Demo struct {
	ABD string `json:"ABD"`
}

type Demo2 struct {
	ABD string `json:"ABD"`
	Abd string `json:"Abd"`
}

func main() {
	var demo Demo
	str := `{"abd": "123", "AbD":"qwe"}`
	//str2 := `{"ABD": "123", "Abd":"qwe"}`
	//str2 := `{"abd": "123", "Abd":"qwe"}`
	//str2 := `{"Abd": "123", "ABD":"qwe"}`
	err := json.Unmarshal([]byte(str), &demo)
	if err != nil {
		fmt.Println("json.Unmarshal err=", err)
	}
	fmt.Printf("%#+v", demo) // main.Demo{ABD:"123"}

	// 可以试试 Demo2 和 str2 的各种组合
	// 总结就是不要使用同名字段(忽视大小写后同名的字段)!!!
	// 特殊情况要用就必须保证 1.结构体要有tag 2.tag与json数据字段名一定要大小写一致
}

posted @ 2022-12-27 15:09  等你下课啊  阅读(759)  评论(0)    收藏  举报