在JSON解组后自动创建计算字段

huangapple go评论83阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年10月23日 17:32:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/33299099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定