Skip to content

Commit

Permalink
Allow case insensitive JSON tag matching
Browse files Browse the repository at this point in the history
The standard library `encoding/json` allows it by default.

Fix #237
  • Loading branch information
cmaglie committed May 4, 2022
1 parent a209843 commit 50149f4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
19 changes: 16 additions & 3 deletions gen/decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ func (g *Generator) interfaceIsJsonUnmarshaller(t reflect.Type) bool {
return t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem())
}

func (g *Generator) genStructFieldDecoder(t reflect.Type, f reflect.StructField) error {
func (g *Generator) genStructFieldDecoder(t reflect.Type, f reflect.StructField, caseSensitive bool) error {
jsonName := g.fieldNamer.GetJSONFieldName(t, f)
tags := parseFieldTags(f)

Expand All @@ -342,7 +342,11 @@ func (g *Generator) genStructFieldDecoder(t reflect.Type, f reflect.StructField)
return errors.New("Mutually exclusive tags are specified: 'intern' and 'nocopy'")
}

fmt.Fprintf(g.out, " case %q:\n", jsonName)
if caseSensitive {
fmt.Fprintf(g.out, " case %q:\n", jsonName)
} else {
fmt.Fprintf(g.out, " case %q:\n", strings.ToLower(jsonName))
}
if err := g.genTypeDecoder(f.Type, "out."+f.Name, tags, 3); err != nil {
return err
}
Expand Down Expand Up @@ -522,12 +526,20 @@ func (g *Generator) genStructDecoder(t reflect.Type) error {

fmt.Fprintln(g.out, " switch key {")
for _, f := range fs {
if err := g.genStructFieldDecoder(t, f); err != nil {
if err := g.genStructFieldDecoder(t, f, true); err != nil {
return err
}
}

fmt.Fprintln(g.out, " default:")
fmt.Fprintln(g.out, " switch strings.ToLower(key) {")
for _, f := range fs {
if err := g.genStructFieldDecoder(t, f, false); err != nil {
return err
}
}
fmt.Fprintln(g.out, " default:")

if g.disallowUnknownFields {
fmt.Fprintln(g.out, ` in.AddError(&jlexer.LexerError{
Offset: in.GetPos(),
Expand All @@ -539,6 +551,7 @@ func (g *Generator) genStructDecoder(t reflect.Type) error {
} else {
fmt.Fprintln(g.out, " in.SkipRecursive()")
}
fmt.Fprintln(g.out, " }")
fmt.Fprintln(g.out, " }")
fmt.Fprintln(g.out, " in.WantComma()")
fmt.Fprintln(g.out, " }")
Expand Down
1 change: 1 addition & 0 deletions gen/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ func NewGenerator(filename string) *Generator {
pkgLexer: "jlexer",
pkgEasyJSON: "easyjson",
"encoding/json": "json",
"strings": "strings",
},
fieldNamer: DefaultFieldNamer{},
marshalers: make(map[reflect.Type]bool),
Expand Down

0 comments on commit 50149f4

Please sign in to comment.