Skip to content

Commit

Permalink
Support json.Number unmarshal
Browse files Browse the repository at this point in the history
  • Loading branch information
Fedott committed Aug 19, 2021
1 parent db98614 commit 7c6540c
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
8 changes: 8 additions & 0 deletions unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (

const tag string = "njson"

var jsonNumberType = reflect.TypeOf(json.Number(""))

// Unmarshal used to unmarshal nested json using "njson" tag
func Unmarshal(data []byte, v interface{}) (err error) {

Expand Down Expand Up @@ -39,6 +41,12 @@ func Unmarshal(data []byte, v interface{}) (err error) {
// get field value by tag
result := gjson.GetBytes(data, typeOfT.Field(i).Tag.Get(tag))

// if field type json.Number
if v != nil && field.Kind() == reflect.String && field.Type() == jsonNumberType {
elem.Field(i).SetString(result.String())
continue
}

var value interface{}
if isStructureType(field.Kind().String()) {
value = parseStructureType(result, field.Type())
Expand Down
62 changes: 62 additions & 0 deletions unmarshal_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package njson

import (
json2 "encoding/json"
"testing"
"time"

Expand Down Expand Up @@ -66,6 +67,67 @@ func TestUnmarshalSmall(t *testing.T) {

}

func TestUnmarshalJsonNumber(t *testing.T) {
json := `
{
"name": {"first": "Mohamed", "last": "Shapan"},
"age": 26,
"weight": "77",
"friends": [
{"first": "Asma", "age": 26},
{"first": "Ahmed", "age": 25},
{"first": "Mahmoud", "age": 30}
]
}`

type Name struct {
First string `njson:"first"`
Last string `njson:"last"`
}

type User struct {
Name Name `njson:"name"`
Age json2.Number `njson:"age"`
Weight json2.Number `njson:"weight"`
Friends []Name `njson:"friends"`
}

actual := User{}

err := Unmarshal([]byte(json), &actual)
if err != nil {
t.Error(err)
}

var friends []Name
friends = append(friends, Name{
First: "Asma",
})

friends = append(friends, Name{
First: "Ahmed",
})

friends = append(friends, Name{
First: "Mahmoud",
})

expected := User{
Name: Name{
First: "Mohamed",
Last: "Shapan",
},
Age: json2.Number("26"),
Weight: json2.Number("77"),
Friends: friends,
}

diff := cmp.Diff(expected, actual)
if diff != "" {
t.Error(diff)
}
}

func TestUnmarshallBasicTypes(t *testing.T) {
json := `
{
Expand Down

0 comments on commit 7c6540c

Please sign in to comment.