doulao1934 2019-08-30 21:29
浏览 342
已采纳

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

I have a JSON file like this:

[
  {   

    "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.

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

Namespace: Name: %!d(string=)

Namespace: Name: %!d(string=)

Here's my code in 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
", 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
", configObj.namespace, configObj.name)
    }
}

Moreover, if I understand the purpose of using omitempty, then it shouldn't even be writing the empty fields. 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?

  • 写回答

1条回答 默认 最新

  • dpk20361 2019-08-30 21:58
    关注

    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. If you marshal your struct to json with empty strings, then those fields will be omitted. If you printf the struct, they will be printed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里