dp518158 2014-10-17 14:00
浏览 39
已采纳

编组时忽略JSON标签

I am getting JSON data from an external source. The field names in this JSON are not something I want to carry with me, so I am converting them to names that make sense to me using the json:"originalname" tags.

When I marshal such an object back to JSON, I naturally get the ugly (original) names again.

Is there a way to ignore tags when marshalling? Or a way to specify a different name for marshall and unmarshall?

To clarify, I have prepared an example in the playground and pasted the same code below.

Thanks in advance.

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}
}
  • 写回答

1条回答 默认 最新

  • dpgkg42484 2014-10-17 14:15
    关注

    You could implement

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

    from the standard library's encoding/json package. Example:

    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) + `}`)
    }
    

    It's admittedly not a very nice solution, though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用