Support custom key name

This commit is contained in:
Masaaki Goshima 2020-04-19 20:28:13 +09:00
parent 936b55a2d3
commit 61c8bdbf27
1 changed files with 10 additions and 1 deletions

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"reflect" "reflect"
"strconv" "strconv"
"strings"
"sync" "sync"
"unsafe" "unsafe"
@ -230,11 +231,19 @@ func (e *Encoder) compileStruct(v reflect.Value) (EncodeOp, error) {
opQueue := make([]EncodeOp, 0, fieldNum) opQueue := make([]EncodeOp, 0, fieldNum)
for i := 0; i < fieldNum; i++ { for i := 0; i < fieldNum; i++ {
field := typ.Field(i) field := typ.Field(i)
keyName := field.Name
tag := field.Tag.Get("json")
opts := strings.Split(tag, ",")
if len(opts) > 0 {
if opts[0] != "" {
keyName = opts[0]
}
}
op, err := e.compile(v.Field(i)) op, err := e.compile(v.Field(i))
if err != nil { if err != nil {
return nil, err return nil, err
} }
key := fmt.Sprintf(`"%s":`, field.Name) key := fmt.Sprintf(`"%s":`, keyName)
opQueue = append(opQueue, func(enc *Encoder, base uintptr) { opQueue = append(opQueue, func(enc *Encoder, base uintptr) {
enc.EncodeString(key) enc.EncodeString(key)
op(enc, base+field.Offset) op(enc, base+field.Offset)