将地图编组为JSON时丢失数据。

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

Missing data when Marshalling map to JSON

问题

我正在尝试将一个名为Foo的结构体转换为JSON,其中包含一个名为Values map[string]CellValue的属性,其中CellValue是另一个结构体。但是,出现了一个问题,生成的JSON不包含CellValue结构体中保存的数据,尽管Values映射中的所有键都是存在的。

这里是一个简单的示例代码,可以在playground上复现这个问题。

我对Go还不太熟悉,有人能找出问题所在吗?

英文:

I'm trying to marshal to JSON a struct Foo that has a Values map[string]CellValue property where CellValue is another struct. For some reason, the resultant JSON does not contain the data held in the CellValue struct even though all the keys in the Values map are present.

Here's a simple playground repro of the issue.

I'm new to Go, can anyone spot the problem here?

答案1

得分: 1

CellValue的字段是未导出的(以小写字符开头)。根据文档(我强调一下),"每个导出的结构字段都成为对象的成员",这意味着在编组或解组时会忽略未导出的值。

英文:

The fields of CellValue are unexported (start with a lowercase character). Per the documentation (emphasis mine), "Each exported struct field becomes a member of the object" - meaning unexported values are ignored when marshaling or unmarshaling.

huangapple
  • 本文由 发表于 2017年6月9日 05:35:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/44445958.html
匿名

发表评论

匿名网友

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

确定