简体   繁体   English

GoLang中的Marshall和UnMarshall JSON内容

[英]Marshall and UnMarshall JSON Content in GoLang

I have a sample json file which is structured like this 我有一个样本json文件,其结构如下

{
  "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. 我正在尝试编写一个可以读取此文件并运行json内容的go程序。

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. res.method和res.gc不打印任何东西。 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). 字段名称必须为大写,否则Json模块无法访问它们(它们对您的模块是私有的)。 You can use the json tag to specify a match between Field and name 您可以使用json标记指定Field和name之间的匹配项

type Response2 struct {
    Method string `json:"method"`
    Bc string `json:"bc"`
    Gc []string `json:"gc"`
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM