简体   繁体   English

如何使用Go将这个JSON数组解组到结构切片中?

[英]How do I unmarshal this JSON array into a struct slice with Go?

I have a JSON file like this: 我有一个像这样的JSON文件:

[
  {   

    "namespace": "pulsarNamespace1",
    "name": "pulsarFunction1",
    "tenant": "pulsarTenant1"
  },

  {   

    "namespace": "pulsarNamespace2",
    "name": "pulsarFunction2",
    "tenant": "pulsarTenant1"
  }
]

I am attempting to deserialize/unmarshal this JSON array into a slice of structs, but I'm getting structs with empty (default) values. 我试图将这个JSON数组反序列化/解组为结构片段,但是我正在获取具有空(默认)值的结构。

When I run my code, it correctly reads my file into a string, but it's not deserializing the data correctly and just writes empty structs to the console, like this: 当我运行代码时,它会正确地将我的文件读入一个字符串中,但是并没有正确地反序列化数据,而是将空结构写入控制台,如下所示:

[]main.Config{main.Config{namespace:"", tenant:"", name:""}, main.Config{namespace:"", tenant:"", name:""}} [] main.Config {main.Config {namespace:“”,租户:“”,名称:“”},main.Config {namespace:“”,租户:“”,名称:“”}}

Namespace: Name: %!d(string=) 命名空间:名称:%!d(string =)

Namespace: Name: %!d(string=) 命名空间:名称:%!d(string =)

Here's my code in Go: 这是我在Go中的代码:

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "os"
) 
// Ignore the unused imports.

type Config struct {
    namespace string `json:"namespace,omitempty"`
    tenant    string `json:"tenant,omitempty"`
    name      string `json:"name,omitempty"`
}

func getConfigs() string {
    b, err := ioutil.ReadFile("fastDeploy_example.json") // just pass the file name
    if err != nil {
        fmt.Print(err)
    }
    str := string(b) // convert content to a 'string'
    fmt.Println(str) // print the content as a 'string'
    return str
}

func deserializeJson(configJson string) []Config {
    jsonAsBytes := []byte(configJson)
    configs := make([]Config, 0)
    err := json.Unmarshal(jsonAsBytes, &configs)
    fmt.Printf("%#v\n", configs)
    if err != nil {
        panic(err)
    }
    return configs
}

func main() {
    // Unmarshal each fastDeploy config component into a slice of structs.
    jsonConfigList := getConfigs()
    unmarshelledConfigs := deserializeJson(jsonConfigList)

    for _, configObj := range unmarshelledConfigs {
        fmt.Printf("Namespace: %s Name: %d\n", configObj.namespace, configObj.name)
    }
}

Moreover, if I understand the purpose of using omitempty , then it shouldn't even be writing the empty fields. 而且,如果我了解使用omitempty的目的,那么它甚至不应该写入空白字段。 However, it appears that it's writing them anyway. 但是,看来它还是在写它们。

How do I correctly deserialize/unmarshal my JSON array into my slice of structs in Golang? 如何在Golang中将JSON数组正确反序列化/解组到我的结构片中?

Export the field names of your struct: Namespace, Tenant, Name, etc., so the unmarshaler can set them via reflection. 导出结构的字段名称:命名空间,租户,名称等,以便拆组器可以通过反射对其进行设置。

Re: omitempty, that's a tag for the json marshaler. 回复:omitempty,这是json marshaler的标签。 If you marshal your struct to json with empty strings, then those fields will be omitted. 如果使用空字符串将结构封送至json,则这些字段将被省略。 If you printf the struct, they will be printed. 如果您打印该结构,则将打印它们。

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

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