将JSON数组转换为Go结构体

huangapple go评论71阅读模式
英文:

JSON Arrays as Go Structs

问题

我正在尝试从我的JSON文件中调用一个对象数组,但我总是遇到一个错误,提示“无法将数组解组为类型为config.APPConfig的Go值”。我该如何确保我的Go结构调用JSON文件中的对象数组?以下是我设置Go结构的配置文件和JSON文件的内容:

Config.go

package config

import (
	"encoding/json"
	"io/ioutil"
)

type Easy struct {
	UID string `json:"uId"`
}

type Auth struct {
	Code string `json:"code"`
}

type APPConfig struct {
	OpenAPIMode string `json:"openAPIMode"`
	OpenAPIURL  string `json:"openAPIUrl"`

	ClientID string `json:"clientId"`
	Secret   string `json:"secret"`

	AuthMode string `json:"authMode"`

	Easy Easy `json:"easy"`
	Auth Auth `json:"auth"`

	DeviceID string `json:"deviceId"`

	UID          string `json:"-"`
	MQTTUID      string `json:"-"`
	AccessToken  string `json:"-"`
	RefreshToken string `json:"-"`
	ExpireTime   int64  `json:"-"`
}

var App = APPConfig{
	OpenAPIMode: "mqtt",
	OpenAPIURL:  "openapi.tuyacn.com",
}

func LoadConfig() error {
	return parseJSON("webrtc.json", &App)
}

func parseJSON(path string, v interface{}) error {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	err = json.Unmarshal(data, v)
	return err
}

JSON文件

[
  {
    "openAPIMode": "mqtt",
    "openAPIUrl": "openapi.tuyaus.com",
    "clientId": "*****",
    "secret": "**************",
    "authMode": "easy",
    "easy": {
      "uId": "**********"
    },
    "auth": {
      "code": ""
    },
    "deviceId": "***********"
  },
  {
    "openAPIMode": "mqtt",
    "openAPIUrl": "openapi.tuyaus.com",
    "clientId": "*****",
    "secret": "**************",
    "authMode": "easy",
    "easy": {
      "uId": "**********"
    },
    "auth": {
      "code": ""
    },
    "deviceId": "***********"
  }
]

提前感谢您的帮助!

英文:

I am trying to call an array of objects from my JSON file but I am always facing an error saying: "cannot unmarshal array into Go value of type config.APPConfig".
How can I ensure the configs how my Go struct calls the array of objects within my JSON file?
Here are both my config file in which I set up the Go structs and the JSON file:

Config.go

package config

import (
 "encoding/json"
 "io/ioutil"
)

type Easy struct {
 UID string `json:"uId"`
}

type Auth struct {
 Code string `json:"code"`
}

type APPConfig struct {
 OpenAPIMode string `json:"openAPIMode"` 
 OpenAPIURL  string `json:"openAPIUrl"`  

 ClientID string `json:"clientId"` 
 Secret   string `json:"secret"` 

 AuthMode string `json:"authMode"`

 Easy Easy `json:"easy"`
 Auth Auth `json:"auth"`

 DeviceID string `json:"deviceId"`

 UID          string `json:"-"` 
 MQTTUID      string `json:"-"` 
 AccessToken  string `json:"-"`
 RefreshToken string `json:"-"`
 ExpireTime   int64  `json:"-"`
}

var App = APPConfig{
  OpenAPIMode: "mqtt",
  OpenAPIURL:  "openapi.tuyacn.com",
}


func LoadConfig() error {
  return parseJSON("webrtc.json", &App)
}

func parseJSON(path string, v interface{}) error {
  data, err := ioutil.ReadFile(path)
  if err != nil {
	return err
}

 err = json.Unmarshal(data, v)
 return err
}

JSON file

[
  {
    "openAPIMode": "mqtt",
    "openAPIUrl": "openapi.tuyaus.com",
    "clientId": "*****",
    "secret": "**************",
    "authMode": "easy",
    "easy": {
      "uId": "**********"
    },
    "auth": {
      "code": ""
    },
    "deviceId": "***********"
  },
  {
    "openAPIMode": "mqtt",
    "openAPIUrl": "openapi.tuyaus.com",
    "clientId": "*****",
    "secret": "**************",
    "authMode": "easy",
    "easy": {
      "uId": "**********"
    },
    "auth": {
      "code": ""
    },
    "deviceId": "***********"
  }
]

Thanks in advance for helping!

答案1

得分: 1

你的配置 JSON 文件是一个 JSON 数组,你正在将其解析为结构体,但你需要将其解析为结构体数组。

要修复你的代码,将 App 的初始化更改为以下内容:

var App []APPConfig

func LoadConfig() error {
	return parseJSON("webrtc.json", &App)
}

以下是完整的示例代码:

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
)

type Easy struct {
	UID string `json:"uId"`
}

type Auth struct {
	Code string `json:"code"`
}

type APPConfig struct {
	OpenAPIMode string `json:"openAPIMode"`
	OpenAPIURL  string `json:"openAPIUrl"`

	ClientID string `json:"clientId"`
	Secret   string `json:"secret"`

	AuthMode string `json:"authMode"`

	Easy Easy `json:"easy"`
	Auth Auth `json:"auth"`

	DeviceID string `json:"deviceId"`

	UID          string `json:"-"`
	MQTTUID      string `json:"-"`
	AccessToken  string `json:"-"`
	RefreshToken string `json:"-"`
	ExpireTime   int64  `json:"-"`
}

var App []APPConfig

func LoadConfig() error {
	return parseJSON("webrtc.json", &App)
}

func parseJSON(path string, v interface{}) error {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	err = json.Unmarshal(data, v)
	return err
}

func main() {
	err := LoadConfig()
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", App)
}

希望对你有帮助!

英文:

Your config json file is an Array of JSON and you are parsing it to struct you need to parse it to array of struct.

To fix your code change the initialization of App to this.

var App []APPConfig

func LoadConfig() error {
	return parseJSON("webrtc.json", &App)
}

Here's example full code for it.

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
)

type Easy struct {
	UID string `json:"uId"`
}

type Auth struct {
	Code string `json:"code"`
}

type APPConfig struct {
	OpenAPIMode string `json:"openAPIMode"`
	OpenAPIURL  string `json:"openAPIUrl"`

	ClientID string `json:"clientId"`
	Secret   string `json:"secret"`

	AuthMode string `json:"authMode"`

	Easy Easy `json:"easy"`
	Auth Auth `json:"auth"`

	DeviceID string `json:"deviceId"`

	UID          string `json:"-"`
	MQTTUID      string `json:"-"`
	AccessToken  string `json:"-"`
	RefreshToken string `json:"-"`
	ExpireTime   int64  `json:"-"`
}

var App []APPConfig

func LoadConfig() error {
	return parseJSON("webrtc.json", &App)
}

func parseJSON(path string, v interface{}) error {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	err = json.Unmarshal(data, v)
	return err
}

func main() {
	err := LoadConfig()
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", App)
}

huangapple
  • 本文由 发表于 2022年12月9日 10:27:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/74738341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定