drgc9632
drgc9632
2018-09-14 00:34

json解组不工作,但解码

已采纳

I have a hard time understanding why that code below which uses the unmarshal method does not work, but then almost the same i write with NewDecoder and it work find.

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
}

but if i do all the same but instead of the two last lines with the byteValue and the unmarshal itself, but use the decoder, it works,

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

Thanks!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanhan7001 duanhan7001 3年前

    I would guess that you need to pass a pointer to the configuration, like so:

    json.Unmarshal(byteValue, &configuration)
    

    You should also check the error value returned by Unmarshal, e.g.:

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

    See the the docs.

    点赞 评论 复制链接分享