JSON 解组后自动创建计算字段
Automatically create computed fields after JSON unmarshalling
简化示例
假设我有一个结构,我用它来解组一些 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:
填充结构后调用 if
// Grab data
request, _ := http.Get("http://........")
var entry DataEntry
dec := json.NewDecoder(request.Body)
dec.Decode(&entry)
// Compute the computed fields
entry.Compute()
有更好的方法吗?我可以创建自己的 UnmarshalJSON
并将其用作自动计算 FullName
字段的触发器吗?
在这种情况下,我会把 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
}
简化示例
假设我有一个结构,我用它来解组一些 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:
填充结构后调用 if// Grab data
request, _ := http.Get("http://........")
var entry DataEntry
dec := json.NewDecoder(request.Body)
dec.Decode(&entry)
// Compute the computed fields
entry.Compute()
有更好的方法吗?我可以创建自己的 UnmarshalJSON
并将其用作自动计算 FullName
字段的触发器吗?
在这种情况下,我会把 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
}