Skip to content

Commit 50149f4

Browse files
committed
Allow case insensitive JSON tag matching
The standard library `encoding/json` allows it by default. Fix #237
1 parent a209843 commit 50149f4

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

gen/decoder.go

+16-3
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@ func (g *Generator) interfaceIsJsonUnmarshaller(t reflect.Type) bool {
331331
return t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem())
332332
}
333333

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

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

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

523527
fmt.Fprintln(g.out, " switch key {")
524528
for _, f := range fs {
525-
if err := g.genStructFieldDecoder(t, f); err != nil {
529+
if err := g.genStructFieldDecoder(t, f, true); err != nil {
526530
return err
527531
}
528532
}
529533

530534
fmt.Fprintln(g.out, " default:")
535+
fmt.Fprintln(g.out, " switch strings.ToLower(key) {")
536+
for _, f := range fs {
537+
if err := g.genStructFieldDecoder(t, f, false); err != nil {
538+
return err
539+
}
540+
}
541+
fmt.Fprintln(g.out, " default:")
542+
531543
if g.disallowUnknownFields {
532544
fmt.Fprintln(g.out, ` in.AddError(&jlexer.LexerError{
533545
Offset: in.GetPos(),
@@ -539,6 +551,7 @@ func (g *Generator) genStructDecoder(t reflect.Type) error {
539551
} else {
540552
fmt.Fprintln(g.out, " in.SkipRecursive()")
541553
}
554+
fmt.Fprintln(g.out, " }")
542555
fmt.Fprintln(g.out, " }")
543556
fmt.Fprintln(g.out, " in.WantComma()")
544557
fmt.Fprintln(g.out, " }")

gen/generator.go

+1
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ func NewGenerator(filename string) *Generator {
6565
pkgLexer: "jlexer",
6666
pkgEasyJSON: "easyjson",
6767
"encoding/json": "json",
68+
"strings": "strings",
6869
},
6970
fieldNamer: DefaultFieldNamer{},
7071
marshalers: make(map[reflect.Type]bool),

0 commit comments

Comments
 (0)