猿问

编组时忽略 JSON 标签

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


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


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


为了澄清起见,我在操场上准备了一个示例,并在下面粘贴了相同的代码。


提前致谢。


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}

}


紫衣仙女
浏览 183回答 2
2回答

富国沪深

你可以实施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) + `}`)}诚然,这不是一个很好的解决方案。
随时随地看视频慕课网APP

相关分类

Go
我要回答