代码之家  ›  专栏  ›  技术社区  ›  Max

json解组不起作用,但解码起作用

  •  -1
  • Max  · 技术社区  · 8 年前

    package conf
    
    import (
        "os"
        "io/ioutil"
        "encoding/json"
    )
    
    type Configuration struct {
        Agents []Agent `json:"agents"`
        IbmWmqFolder string `json:"ibmWmqFolder"`
    }
    
    type Agent struct {
        AgentName string `json:"agentName"`
        Folders []string `json:"folders"`
    }
    
    func LoadConfiguration() (configuration Configuration) {
        jsonFile, err := os.Open("config.json")
        if err != nil {
            panic(err)
        }
        defer jsonFile.Close()
        byteValue, _ := ioutil.ReadAll(jsonFile)
        json.Unmarshal(byteValue, configuration)
        return
    }
    

    但如果我也这么做,但不是最后两行 byteValue

    jsonParser := json.NewDecoder(jsonFile)
    jsonParser.Decode(&configuration)
    return
    

    1 回复  |  直到 8 年前
        1
  •  5
  •   kristianp    8 年前

    我猜您需要向配置传递一个指针,如下所示:

    json.Unmarshal(byteValue, &configuration)
    

    您还应该检查Unmarshal返回的错误值,例如:

    err = json.Unmarshal(byteValue, &configuration)
    if err != nil {
        panic(err)
    }
    

    看到了吗 the docs .