This question already has answers here:
Printing Empty Json as a result [duplicate]

(1个答案)



json.Marshal(struct) returns “{}”

(3个答案)


去年关闭。




我有一个非常简单的程序,如下所示:
package main

import (
    "encoding/json"
    "fmt"
)

type RunCommand struct{
    level string `json:"level"`
    caller string `json:"caller"`
    msg string `json:"msg"`
    cmd string `json:"cmd"`
}

func main() {
    content := `{"level":"info","caller":"my.go:10","msg":"run","cmd":"--parse"}`
    runCommand := RunCommand{}
    e := json.Unmarshal([]byte(content), &runCommand)
    if e != nil {
        fmt.Println("Unmarshal error")
    }
    fmt.Println(runCommand.level)
}

我希望我可以将“内容”内的所有json字段解析为“runCommand”对象,但实际上,最终的“fmt.Println”不会打印任何内容。我在哪里弄错了?

最佳答案

您必须具有导出字段,如下所示:

type RunCommand struct{
    Level string `json:"level"`
    Caller string `json:"caller"`
    Msg string `json:"msg"`
    Cmd string `json:"cmd"`
}

现在您可以使用:fmt.Println(runCommand.Level)否则json.Unmarshal将忽略未导出的字段。

09-04 20:18