Skip to content

Commit fa5f730

Browse files
committed
Fix unmarshalAttribute to support unmarshaling into a json.RawMessage
1 parent 0af5cf6 commit fa5f730

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

request.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,11 @@ func unmarshalAttribute(
393393
return
394394
}
395395

396+
// Handle field of type json.RawMessage
397+
if fieldValue.Type() == reflect.TypeOf(json.RawMessage{}) {
398+
value, err = handleJSONRawMessage(attribute)
399+
}
400+
396401
// Handle field of type time.Time
397402
if fieldValue.Type() == reflect.TypeOf(time.Time{}) ||
398403
fieldValue.Type() == reflect.TypeOf(new(time.Time)) {
@@ -444,6 +449,14 @@ func handleStringSlice(attribute interface{}) (reflect.Value, error) {
444449
return reflect.ValueOf(values), nil
445450
}
446451

452+
func handleJSONRawMessage(attribute interface{}) (reflect.Value, error) {
453+
tmp, err := json.Marshal(attribute)
454+
if err != nil {
455+
return reflect.Value{}, err
456+
}
457+
return reflect.ValueOf(json.RawMessage(tmp)), nil
458+
}
459+
447460
func handleTime(attribute interface{}, args []string, fieldValue reflect.Value) (reflect.Value, error) {
448461
var isIso8601 bool
449462
v := reflect.ValueOf(attribute)

request_test.go

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1320,7 +1320,8 @@ func (mca *MyCustomAttribute) UnmarshalJSON(bts []byte) error {
13201320

13211321
type StructForTest struct {
13221322
ID string `jsonapi:"primary,tests"`
1323-
Custom MyCustomAttribute `jsonapi:"attr,custom"`
1323+
Custom MyCustomAttribute `jsonapi:"attr,custom,omitempty"`
1324+
Raw json.RawMessage `jsonapi:"attr,raw,omitempty"`
13241325
}
13251326

13261327
func TestUnmarshalWithCustomType(t *testing.T) {
@@ -1347,3 +1348,33 @@ func TestUnmarshalWithCustomType(t *testing.T) {
13471348
sft.Custom.Field, newSft.Custom.Field)
13481349
}
13491350
}
1351+
1352+
func TestUnmarshalWithJSONRawMessage(t *testing.T) {
1353+
tests := [][]byte{
1354+
[]byte(`{"really":{"deep":true},"test":"toast"}`),
1355+
[]byte(`"just a string"`),
1356+
[]byte(`123`),
1357+
}
1358+
for _, v := range tests {
1359+
sft := &StructForTest{
1360+
ID: "my-id",
1361+
Raw: v,
1362+
}
1363+
buf := new(bytes.Buffer)
1364+
err := MarshalPayload(buf, sft)
1365+
if err != nil {
1366+
t.Fatal(err)
1367+
}
1368+
newSft := &StructForTest{}
1369+
err = UnmarshalPayload(buf, newSft)
1370+
1371+
if err != nil {
1372+
t.Fatal(err)
1373+
}
1374+
1375+
if bytes.Compare(sft.Raw, newSft.Raw) != 0 {
1376+
t.Fatalf("json.RawMessage wasn't properly unmarshalled: Expected to have `%s` but got `%s`",
1377+
string(sft.Raw), string(newSft.Raw))
1378+
}
1379+
}
1380+
}

0 commit comments

Comments
 (0)