gpt4 book ai didi

json - 编码时忽略 JSON 标签

转载 作者:IT王子 更新时间:2023-10-29 01:33:49 26 4
gpt4 key购买 nike

我正在从外部来源获取 JSON 数据。我不想随身携带此 JSON 中的字段名称,因此我使用 json:"originalname" 标记将它们转换为对我有意义的名称。

当我将这样的对象编码回 JSON 时,我自然会再次获得丑陋的(原始)名称。

有没有办法在编码时忽略标签?或者为 marshall 和 unmarshall 指定不同名称的方法?

为了澄清,我准备了一份 example in the playground并在下面粘贴相同的代码。

提前致谢。

package main

import (
"encoding/json"
"fmt"
)

type Band struct {
Name string `json:"bandname"`
Albums int `json:"albumcount"`
}

func main() {
// JSON -> Object
data := []byte(`{"bandname": "AC/DC","albumcount": 10}`)
band := &Band{}
json.Unmarshal(data, band)

// Object -> JSON
str, _ := json.Marshal(band)
fmt.Println("Actual Result: ", string(str))
fmt.Println("Desired Result:", `{"Name": "AC/DC","Albums": 10}`)

// Output:
// Actual Result: {"bandname":"AC/DC","albumcount":10}
// Desired Result: {"Name": "AC/DC","Albums": 10}
}

最佳答案

你可以实现

type Marshaler interface {
MarshalJSON() ([]byte, error)
}

来自标准库的 encoding/json 包。示例:

type Band struct {
Name string `json:"bandname"`
Albums int `json:"albumcount"`
}

func (b Band) MarshalJSON() ([]byte, error) {
n, _ := json.Marshal(b.Name)
a, _ := json.Marshal(b.Albums)
return []byte(`{"Name":` + string(n) + `,"Albums":` + string(a) + `}`)
}

不过,这确实不是一个很好的解决方案。

关于json - 编码时忽略 JSON 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26426746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com