英文:
Automatically create computed fields after JSON unmarshalling
问题
Simplified example
假设我有一个结构体,用于解析一些 JSON 数据:
type DataEntry struct {
FirstName string `json:"first"`
LastName string `json:"last"`
FullName string
}
我想要填充FullName
属性,即FirstName + LastName
。
目前我正在做的是为DataEntry
定义一个方法,用于执行这些计算:
func (de *DataEntry) Compute() {
de.FullName = de.FirstName + " " + de.LastName
}
并在结构体从 JSON 中填充后调用该方法:
// 获取数据
request, _ := http.Get("http://........")
var entry DataEntry
dec := json.NewDecoder(request.Body)
dec.Decode(&entry)
// 计算衍生字段
entry.Compute()
有没有更好的方法来实现这个?我能否创建自己的UnmarshalJSON
方法,并将其用作自动计算FullName
字段的触发器?
英文:
Simplified example
Lets say I have a struct which I use to unmarshall some json:
type DataEntry struct {
FirstName string `json:"first"`
LastName string `json:"last"`
FullName string
}
What I want to fill the FullName
property, which would be FirstName + LastName
.
What I am currently doing is defining a method for DataEntry, which does these kind of computations:
func (de *DataEntry) Compute() {
de.FullName = de.FirstName + " " + de.LastName
}
and calling if after the struct gets filled from the JSON:
// Grab data
request, _ := http.Get("http://........")
var entry DataEntry
dec := json.NewDecoder(request.Body)
dec.Decode(&entry)
// Compute the computed fields
entry.Compute()
Is there a better way to do this? Could I use create my own UnmarshalJSON
and use that as a trigger to automatically compute the FullName
field?
答案1
得分: 3
在这种情况下,我会将FullName
转换为一个方法。但如果你真的需要这样做,只需创建一个包装类型,该类型也是json.Unmarshaler
:
type DataEntryForJSON DataEntry
func (d *DataEntryForJSON) UnmarshalJSON(b []byte) error {
if err := json.Unmarshal(b, (*DataEntry)(d)); err != nil {
return err
}
d.FullName = d.FirstName + " " + d.LastName
return nil
}
Playground: http://play.golang.org/p/g9BnytB5DG.
英文:
In this case I would just turn FullName
into a method. But if you really need to make it that way, just create a wrapper type that is also a json.Unmarshaler
:
type DataEntryForJSON DataEntry
func (d *DataEntryForJSON) UnmarshalJSON(b []byte) error {
if err := json.Unmarshal(b, (*DataEntry)(d)); err != nil {
return err
}
d.FullName = d.FirstName + " " + d.LastName
return nil
}
Playground: http://play.golang.org/p/g9BnytB5DG.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论