去json.Unmarshal返回false struct

时间:2017-01-08 18:40:41

标签: json go struct unmarshalling

Golang新手在这里

我正在尝试从.json文件(与Go代码在同一目录中)解析成一个包含其他结构的结构,而最接近成功的是一个包含布尔值false的结构,这对我来说听起来很糟糕

到目前为止,这是我在Go代码中的内容

package main

import (
    "encoding/json"
    "fmt"

    "io/ioutil"
)

type App struct {
    Name string `json:"app:name"`
}

type Database struct {
    Type     string `json:"database:type"`
    Name     string `json:"database:name"`
    User     string `json:"database:user"`
    Password string `json:"database:password"`
}

type Environment struct {
    Mode  string `json:"environment:mode"`
    Debug bool   `json:"environment:debug"`
}

type Config struct {
    Environment Environment
    App         App
    Database    Database
}

func main() {
    config, err := ioutil.ReadFile("config.json")
    if err != nil {
        fmt.Errorf("Error reading config file: %s", err)
    }

    var appSettings Config
    json.Unmarshal(config, &appSettings)

    fmt.Print(appSettings)
}

这是我的.json文件的内容

{
  "App": {
    "Name": "My_Project"
  },
  "Database": {
    "Type": "postgres",
    "Name": "my_project_db_name",
    "User": "my_project_db_user",
    "Password": "secret"
  },
  "Environment": {
    "Mode": "development",
    "Debug": true
  }
}

编辑: 这是main()

末尾的印刷结果

{{ false} {} { }}

我已经验证了json内容,这很好。正在导出结构名称和属性。你能看出我做错了吗?

1 个答案:

答案 0 :(得分:5)

你能尝试这样改变:

type App struct {
    Name string `json:"name"`
}

type Database struct {
    Type     string `json:"type"`
    Name     string `json:"name"`
    User     string `json:"user"`
    Password string `json:"password"`
}

type Environment struct {
    Mode  string `json:"mode"`
    Debug bool   `json:"debug"`
}

这是输出:

{{development true} {My_Project} {postgres my_project_db_name my_project_db_user secret}}

这是一个方便参考的小文档:

// Field is ignored by this package.
Field int `json:"-"`

// Field appears in JSON as key "myName".
Field int `json:"myName"`

// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`

// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`