json - 如何使用结构的类型而不是 go 中的标签重新编组结构?
问题描述
我想将结构重新编组为 json,并使用结构中定义的类型作为输出。结构:
type A struct{
B []B //edit: fields have to be exported to work
}
type B struct{
X string `json:"x"` //edit: fields have to be exported to work
Y float64 `json:"y,string"` //edit: fields have to be exported to work
Z float64 `json:"z,string"` //edit: fields have to be exported to work
如果使用这些结构解组,我会得到 By 作为 float64,正如预期的那样。但是,如果我再次将其重新编组为 JSON,我会得到我解组的 JSON,其中 y 和 z 作为字符串,但我想将它们作为 float64。我必须添加 ',string' 部分,因为 API 在 JSON 响应中将所有内容都作为字符串返回(参见下面的示例)。我是否必须编写一个自定义编组函数来执行此操作,或者我可以将 json 标记添加到结构定义中吗?
示例响应和重新编组的 json:
{
"A": [
{
"x": "test1",
"y": "1.00",
"z": "1.01"
},
{
"x": "test2",
"y": "2.00",
"z": "2.01"
}
]
}
预期的重新编组 JSON:
{
"A": [
{
"x": "test1",
"y": 1.00,
"z": 1.01
},
{
"x": "test2",
"y": 2.00,
"z": 2.01
}
]
}
解决方案
您根本无法编组或解组这些字段,因为这些字段未导出。但是要执行您所描述的操作,只需转换为没有(或不同)结构标记的等效类型。因为它是一个嵌套切片,所以您必须对其进行迭代。
func main() {
a := A{}
err := json.Unmarshal(corpus, &a)
if err != nil {
panic(err)
}
c := C{}
for _, b := range a.B {
c.B = append(c.B, D(b))
}
payload, _ := json.Marshal(c)
fmt.Println(string(payload))
}
type A struct {
B []B
}
type B struct {
X string `json:"x"`
Y float64 `json:"y,string"`
Z float64 `json:"z,string"`
}
type C struct {
B []D
}
type D struct {
X string `json:"x"`
Y float64 `json:"y"`
Z float64 `json:"z"`
}
工作场所示例: https: //play.golang.org/p/pQTcg0RV_RL
推荐阅读
- vue.js - VeeValidate 确认规则因自定义验证器而失败
- git - 将提交移动到不同的分支
- matlab - 为什么在 FFT matlab 示例中执行此操作?
- android - 更改视图的不透明度/透明度并影响子视图
- matlab - “无法执行操作(更新切片窗口)”是什么意思?在 Matlab 的 CellTracker 中是什么意思?
- python - Python 3:使用带有列表 Windows 文件路径的正则表达式作为在特定位置具有数字的字符串
- angular - Angular 6:从子组件侧导航单击滚动到元素
- database - Oracle dB - 包含 GUI 到 dB 链接详细信息的系统表
- json - 从 JSON 响应中获取 TranscriptFileUri
- curl - 通过rest api创建k8s秘密时出错