简体   繁体   English

Go json.Unmarshal返回假结构

[英]Go json.Unmarshal returns false struct

Golang newbie here Golang新手在这里

I'm trying to parse from a .json file (in the same directory as the Go code) into a struct holding other structs and the closest I can get to success is a struct containing boolean false, which sounds broken to me. 我正在尝试从.json文件(与Go代码位于同一目录中)解析为包含其他结构的结构,而我能成功获得的最接近的结构是包含布尔值false的结构,这对我来说听起来很糟糕。

Here's what I have in my Go code so far 到目前为止,这就是我的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)
}

and here's the contents of my .json file 这是我的.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
  }
}

EDIT: Here's the result of the print at the end of main() 编辑:这是在main()末尾打印的结果

{{ false} {} { }}

I have already validated the json content which is fine. 我已经验证了json内容,这很好。 The struct names and properties are being exported. 结构名称和属性正在导出。 Can you see what I'm doing wrong? 你能看到我做错了吗?

Can you try by changing like this: 您可以尝试通过以下方式进行更改:

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"`
}

Here is the output: 这是输出:

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

Here is a little docs for handy reference: 这里有一些文档供您参考:

// 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"`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM