gpt4 book ai didi

json unmarshal 不工作但解码确实

转载 作者:数据小太阳 更新时间:2023-10-29 03:30:35 28 4
gpt4 key购买 nike

我很难理解为什么下面使用 unmarshal 方法的代码不起作用,但我用 NewDecoder 编写的代码几乎相同,而且运行良好。

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

谢谢!

最佳答案

我猜你需要传递一个指向配置的指针,像这样:

json.Unmarshal(byteValue, &configuration)

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

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

参见 the docs .

关于json unmarshal 不工作但解码确实,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52323462/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com