GoLang的Marshall和UnMarshall JSON内容 [英] Marshall and UnMarshall JSON Content in GoLang
本文介绍了GoLang的Marshall和UnMarshall JSON内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ b
{
method:brute_force ,
bc:select * from blah;,
gc:[
从blah中选择sum(year);,
select count(* )从桌上;
]
}
我正在编写一个可以阅读的go程序
包主
导入(
fmt
encoding / json
io / ioutil
)
类型Response2结构体{
方法字符串
bc字符串
gc [] string
}
func main(){
file,_:= ioutil.ReadFile(config.json)
fmt.Printf (%s,string(file))
res:=& Response2 {}
$ b json.Unmarshal([] byte(string ))& res)
fmt.Println(res)
fmt.Println(res.method)
fmt.Println(res.gc)
}
res.method和res.gc不会打印任何内容。
解决方案
类型Response2结构{
方法字符串
bc字符串
gc []字符串
}
字段的名称必须是大写的,否则Json模块将无法访问它们(它们对您的模块是私有的)。
您可以使用json标记指定字段和名称之间的匹配。
type Response2 struct {
方法字符串`json:method`
Bc字符串`json:bc`
Gc [] string`json:gc`
}
I have a sample json file which is structured like this
{
"method":"brute_force",
"bc":"select * from blah;",
"gc":[
"select sum(year) from blah;",
"select count(*) from table;"
]
}
I am trying to write a go program which can read this file and operate of json content.
package main
import (
"fmt"
"encoding/json"
"io/ioutil"
)
type Response2 struct {
method string
bc string
gc []string
}
func main() {
file,_ := ioutil.ReadFile("config.json")
fmt.Printf("%s",string(file))
res := &Response2{}
json.Unmarshal([]byte(string(file)), &res)
fmt.Println(res)
fmt.Println(res.method)
fmt.Println(res.gc)
}
res.method and res.gc dont print anything. I have no idea on whats going wrong.
解决方案
type Response2 struct {
method string
bc string
gc []string
}
The name of the fields Must be Uppercase otherwise the Json module can't access them (they are private to your module). You can use the json tag to specify a match between Field and name
type Response2 struct {
Method string `json:"method"`
Bc string `json:"bc"`
Gc []string `json:"gc"`
}
这篇关于GoLang的Marshall和UnMarshall JSON内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文