gpt4 book ai didi

json - 编码 JSON 时如何内联字段?

转载 作者:IT王子 更新时间:2023-10-29 02:32:42 27 4
gpt4 key购买 nike

我有一个类型 MonthYear 定义如下

type MonthYear time.Time

func (my *MonthYear) MarshalJSON() ([]byte, error) {
t := time.Time(*my)

return json.Marshal(&struct {
Month int `json:"month"`
Year int `json:"year"`
}{
Month: int(t.Month()) - 1,
Year: t.Year(),
})
}

我在其中包含了很多不同的结构,例如

type Event struct {
Name string `json:"name"`
Date MonthYear
}

type Item struct {
Category string `json:"category"`
Date MonthYear
}

如何内联 MonthYear 类型,以便生成的 JSON 不包含任何嵌入对象?

我希望结果看起来像 { "name": "party", "month": 2, "year": 2017 }{ "category": "art", "month": 3, "year": 2016 无需为每个结构编写 MarshalJSON。

最佳答案

我知道这不是您希望收到的答案,但在将内联支持添加到 encoding/json 之前包,您可以使用以下解决方法:

让你的 MonthYear 成为一个结构体,例如:

type MonthYear struct {
t time.Time
Month int `json:"month"`
Year int `json:"year"`
}

一个可选的构造函数,便于创建:

func NewMonthYear(t time.Time) MonthYear {
return MonthYear{
t: t,
Month: int(t.Month()) - 1,
Year: t.Year(),
}
}

并使用 embedding (匿名字段)而不是常规(命名)字段以在 JSON 表示中“扁平化”/内联:

type Event struct {
Name string `json:"name"`
MonthYear
}

type Item struct {
Category string `json:"category"`
MonthYear
}

此外,您还可以直接引用字段,例如 Event.YearEvent.Month,这很好。

测试它:

evt := Event{Name: "party", MonthYear: NewMonthYear(time.Now())}
fmt.Println(json.NewEncoder(os.Stdout).Encode(evt), evt.Year)

itm := Item{Category: "Tool", MonthYear: NewMonthYear(time.Now())}
fmt.Println(json.NewEncoder(os.Stdout).Encode(itm))

输出(在 Go Playground 上尝试):

{"name":"party","month":10,"year":2009}
<nil> 2009
{"category":"Tool","month":10,"year":2009}
<nil>

注意:MonthYear.t 时间字段在这里不起作用(它也未编码)。如果不需要原始的 time.Time,您可以将其删除。

关于json - 编码 JSON 时如何内联字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43077665/

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