如何将地图添加到用于反序列化 JSON 配置的相同结构中?

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

How to add map into the same struct which is used to deserialize json configs?

问题

我正在将json反序列化为下面显示的结构体,并且它运行良好。

type DataConfigs struct {
    ClientMetrics []Client `json:"ClientMetrics"`
}

type Client struct {
    ClientId int `json:"clientId"`
    // ...
    // ...
}

const (
    ConfigFile = "clientMap.json"
)

func ReadConfig(path string) (*DataConfigs, error) {
    files, err := utilities.FindFiles(path, ConfigFile)
    // 检查错误

    var dataConfig DataConfigs
    body, err := ioutil.ReadFile(files[0])
    // 检查错误
    err = json.Unmarshal(body, &dataConfig)
    // 检查错误

    return &dataConfig, nil
}

现在,我正在尝试使用上述代码中创建的DataConfigs对象构建一个integerClient的映射。因此,我创建了一个方法来完成这个任务,并修改了ReadConfig方法。

func ReadConfig(path string, logger log.Logger) (*DataConfigs, error) {
    files, err := utilities.FindFiles(path, ConfigFile)
    // 检查错误

    var dataConfig DataConfigs
    body, err := ioutil.ReadFile(files[0])
    // 检查错误
    err = json.Unmarshal(body, &dataConfig)
    // 检查错误

    idx := BuildIndex(dataConfig)
    // 现在如何将idx和dataConfig对象添加到一个结构体中?

    return &dataConfig, nil
}

func BuildIndex(dataConfig DataConfigs) map[int]Client {
    m := make(map[int]Client)
    for _, dataConfig := range dataConfig.ClientMetrics {
        m[dataConfig.ClientId] = dataConfig
    }
    return m
}

我的困惑是-我应该修改DataConfigs结构体以添加idx映射,然后从ReadConfig方法返回该结构体,还是应该创建一个新的结构体来处理这个问题?

基本上,我想返回具有ClientMetrics数组和idx映射的DataConfigs结构体。我应该如何在这里做到这一点?因为我最近才开始使用golang,所以有点困惑。

英文:

I am working on deserializing json into a struct as shown below and it works fine.

type DataConfigs struct {
	ClientMetrics []Client `json:"ClientMetrics"`
}

type Client struct {
	ClientId  int  `json:"clientId"`
	.....
    .....
}

const (
	ConfigFile = "clientMap.json"
)

func ReadConfig(path string) (*DataConfigs, error) {
	files, err := utilities.FindFiles(path, ConfigFile)
  // check for error here
  
	var dataConfig DataConfigs
	body, err := ioutil.ReadFile(files[0])
  // check for error here
	err = json.Unmarshal(body, &dataConfig)
  // check for error here

	return &dataConfig, nil
}

Now I am trying to build a map of integer and Client using DataConfigs object that was created as shown above in the code. So I created a method to do the job as shown below and I modified ReadConfig method to do that too.

func ReadConfig(path string, logger log.Logger) (*DataConfigs, error) {
  files, err := utilities.FindFiles(path, ConfigFile)
  // check for error here
  
  var dataConfig DataConfigs
  body, err := ioutil.ReadFile(files[0])
  // check for error here
  err = json.Unmarshal(body, &dataConfig)
  // check for error here

  idx := BuildIndex(dataConfig)
  // now how to add this idx and dataConfig object in one struct?
  
  return &dataConfig, nil
}

func BuildIndex(dataConfig DataConfigs) map[int]Client {
	m := make(map[int]Client)
	for _, dataConfig := range dataConfig.ClientMetrics {
		m[dataConfig.ClientId] = dataConfig
	}
	return m
}

My confusion is - Should I modify DataConfigs struct to add idx map too and then return that struct from ReadConfig method or should I create a new struct to handle that?

Basically I want to return DataConfigs struct which has ClientMetrics array along with idx map. How can I do this here? I am slightly confuse because I started with golang recently.

答案1

得分: 1

这基本上是一个设计问题,有多种选择。首先,我建议避免将地图添加到原始的DataConfigs类型中,因为它与JSON表示不匹配。这可能会导致以后的混淆。

选择哪个选项取决于您的需求和偏好。以下是我脑海中的一些想法:

  1. 您考虑过只返回地图吗?毕竟,您的地图中包含了每个客户端。如果您需要遍历所有客户端,可以遍历地图的所有值。
  2. 第二个选项是除了返回DataConfigs之外,还返回地图。Go语言允许从函数返回多个值,就像您已经为错误处理做的那样。
  3. 最后,您可以将DataConfigs和地图包装在一个新的简单结构类型中,就像您已经猜到的那样。
英文:

This is basically a design question with multiple options. First, I would avoid adding the map to your original DataConfigs type since it does not match the json representation. This could lead to confusion down the road.

Which option to choose depends on your requirements and preferences. Some ideas from the top of my head:

  1. Have you considered returning the map only? After all, you've got every Client in your map. If you need to iterate all Clients you can iterate all values of your map.
  2. Second option is to return the map in addition to DataConfigs. Go allows to return multiple values from a function as you already do for error handling.
  3. Finally, you could wrap DataConfigs and your map in a new simple struct type as you already guessed.

huangapple
  • 本文由 发表于 2022年1月23日 06:41:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/70817738.html
匿名

发表评论

匿名网友

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

确定