encoding/json generator for custom JSON marshalling.
go get -u github.com/daisuzu/encjsongen
encjsongen: Generate MarshalJSON() and UnmarshalJSON() from customjson tag.
Tag format => customjson:"NAME=EXPR;ASSIGN"
- NAME: Used in place of json tag
- EXPR: Expression to represent alias type(for MarshalJSON)
- ASSIGN: Expression to assign to the actual type(for UnmarshalJSON)
Note: "$" in EXPR and ASSIGN is a special character that is converted to
the field name with receiver on the right hand side.
// Example:
type v struct {
CreateTime time.Time `json:"-" customjson:"createTime=$.Unix();time.Unix($, 0)"`
}
Usage: encjsongen [-flag] [package]
Example(by @omohayui)
- user.go
package user
import (
"regexp"
"strings"
"time"
)
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
StartTime time.Time `json:"-" customjson:"createTime=$.Unix();time.Unix($, 0)"`
Text string `json:"-" customjson:"text=lineBreak($);unlineBreak($)"`
Password string `json:"-" customjson:"password=mask($);unmask($)"`
}
var rx = regexp.MustCompile(`[\r\n]`)
func lineBreak(s string) string {
return rx.ReplaceAllString(s, "<br>")
}
func unlineBreak(s string) string {
return strings.Replace(s, "<br>", "\n", -1)
}
func mask(s string) string {
// TODO
return ""
}
func unmask(s string) string {
// TODO
return ""
}
- user_json.go
// Code generated by encjsongen. DO NOT EDIT.
package user
import (
"encoding/json"
"time"
)
func (v *User) MarshalJSON() ([]byte, error) {
type Alias User
return json.Marshal(&struct {
*Alias
AliasStartTime int64 `json:"createTime"`
AliasText string `json:"text"`
AliasPassword string `json:"password"`
}{
Alias: (*Alias)(v),
AliasStartTime: v.StartTime.Unix(),
AliasText: lineBreak(v.Text),
AliasPassword: mask(v.Password),
})
}
func (v *User) UnmarshalJSON(b []byte) error {
type Alias User
aux := &struct {
*Alias
AliasStartTime int64 `json:"createTime"`
AliasText string `json:"text"`
AliasPassword string `json:"password"`
}{
Alias: (*Alias)(v),
}
if err := json.Unmarshal(b, &aux); err != nil {
return err
}
v.StartTime = time.Unix(aux.AliasStartTime, 0)
v.Text = unlineBreak(aux.AliasText)
v.Password = unmask(aux.AliasPassword)
return nil
}