JSON字符串解析到结构体代码示例typeUserstruct{NamestringFansCountint64}如果反序列化的时候指定明确的结构体和变量类型funcTestJsonUnmarshal(ttesting。T){constjsonStream{name:ethancai,fansCount:9223372036854775807}varuserUser类型为Usererr:JsonUnmarshal(jsonStream,user)iferr!nil{fmt。Println(error:,err)}fmt。Printf(v,user)}解析Json数组到切片(数组)typePersonstruct{NamestringAgeint}typeFamilystruct{Persons〔〕Person}解析多维数组varfFamily模拟传输的Json数据familyJSON:{Persons:〔{Name:Elinx,Age:26},{Name:Twinkle,Age:21}〕}fmt。Println()解析字符串为Jsonjson。Unmarshal(〔〕byte(familyJSON),f) 运行结果RUNTestJsonMash{〔{Elinx260001010100:00:000000UTC〔〕}{Twinkle210001010100:00:000000UTC〔〕}〕}{Persons:〔{Name:Elinx,Age:26,Birth:00010101T00:00:00Z,Children:null}PASS:TestJsonMash(0。00s)PASS使用structtag辅助构建json struct能被转换的字段都是首字母大写的字段,但如果想要在json中使用小写字母开头的key,可以使用struct的tag来辅助反射。typePoststruct{Idintjson:IDContentstringjson:contentAuthorstringjson:authorLabel〔〕stringjson:label}funcTestJsonMash1(ttesting。T){postp:Post{2,HelloWorld,userB,〔〕string{linux,shell},}p,:json。MarshalIndent(postp,,)fmt。Println(string(p))} 运行结果:RUNTestJsonMash1{ID:2,content:HelloWorld,author:userB,label:〔linux,shell〕}PASS:TestJsonMash1(0。00s)PASS如何使用tagtag中标识的名称将称为json数据中key的值tag可以设置为json:来表示本字段不转换为json数据,即使这个字段名首字母大写如果想要jsonkey的名称为字符,则可以特殊处理json:,,也就是加上一个逗号如果tag中带有,omitempty选项,那么如果这个字段的值为0值,即false、0、、nil等,这个字段将不会转换到json中如果字段的类型为bool、string、int类、float类,而tag中又带有,string选项,那么这个字段的值将转换成json字符串解析Json数据到结构已知struct{id:1,content:helloworld,author:{id:2,name:userA},published:true,label:〔〕,nextPost:null,comments:〔{id:3,content:goodpost1,author:userB},{id:4,content:goodpost2,author:userC}〕} 测试代码typePoststruct{IDint64json:idContentstringjson:contentAuthorAuthorjson:authorPublishedbooljson:publishedLabel〔〕stringjson:labelNextPostPostjson:nextPostComments〔〕Commentjson:comments}typeAuthorstruct{IDint64json:idNamestringjson:name}typeCommentstruct{IDint64json:idContentstringjson:contentAuthorstringjson:author}funcTestJsonStruct(ttesting。T){jsonData:{id:1,content:helloworld,author:{id:2,name:userA},published:true,label:〔〕,nextPost:null,comments:〔{id:3,content:goodpost1,author:userB},{id:4,content:goodpost2,author:userC}〕}varpostPost解析json数据到post中err:json。Unmarshal(〔〕byte(jsonData),post)iferr!nil{fmt。Println(err)return}fmt。Println(post)fmt。Println(post。Author,post。Content,post。Comments〔0〕。Content,post。Comments〔0〕。ID,post。Comments〔0〕。Author)} 运行结果RUNTestJsonStruct{1helloworld{2userA}true〔〕nil〔0xc00016d1a00xc00016d1d0〕}{2userA}helloworldgoodpost13userBPASS:TestJsonStruct(0。00s)PASS欢迎关注公众号:程序员财富自由之路 在这里插入图片描述参考资料https:www。cnblogs。comfckneedup10080793。html