Skip to content

Commit

Permalink
Sort serialized custom attributes by field name.
Browse files Browse the repository at this point in the history
Add tests for json Marshal/Unmarshal.

Refs #586
  • Loading branch information
echlebek committed Nov 23, 2017
1 parent 81f8ad3 commit 5872eeb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
8 changes: 4 additions & 4 deletions types/dynamic/dynamic.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,8 @@ func ExtractCustomAttributes(v interface{}, msg []byte) ([]byte, error) {
return nil, err
}
objectStarted := false
for field, value := range anys {
_, ok := fields[field]
for _, any := range sortAnys(anys) {
_, ok := fields[any.Name]
if ok {
// Not a custom attribute
continue
Expand All @@ -216,8 +216,8 @@ func ExtractCustomAttributes(v interface{}, msg []byte) ([]byte, error) {
} else {
stream.WriteMore()
}
stream.WriteObjectField(field)
value.WriteTo(stream)
stream.WriteObjectField(any.Name)
any.WriteTo(stream)
}
if !objectStarted {
stream.WriteObjectStart()
Expand Down
31 changes: 31 additions & 0 deletions types/dynamic/dynamic_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dynamic

import (
"encoding/json"
"reflect"
"testing"

Expand Down Expand Up @@ -94,6 +95,25 @@ func (m MyType) Get(name string) (interface{}, error) {
return GetField(m, name)
}

func (m MyType) MarshalJSON() ([]byte, error) {
return Marshal(m)
}

func (m *MyType) UnmarshalJSON(p []byte) error {
type __ MyType
var x __
if err := json.Unmarshal(p, &x); err != nil {
return err
}
*m = MyType(x)
custom, err := ExtractCustomAttributes(m, p)
if err != nil {
return err
}
m.custom = custom
return nil
}

func TestExtractEmptyCustomAttributes(t *testing.T) {
require := require.New(t)
assert := assert.New(t)
Expand Down Expand Up @@ -247,3 +267,14 @@ func TestQueryGovaluateComplex(t *testing.T) {
require.Nil(t, err)
require.Equal(t, true, result)
}

func TestMarshalUnmarshal(t *testing.T) {
data := []byte(`{"bar":null,"foo":"hello","a":10,"b":"c"}`)
var m MyType
err := json.Unmarshal(data, &m)
require.Nil(t, err)
assert.Equal(t, MyType{Foo: "hello", custom: []byte(`{"a":10,"b":"c"}`)}, m)
b, err := json.Marshal(m)
require.Nil(t, err)
assert.Equal(t, data, b)
}

0 comments on commit 5872eeb

Please sign in to comment.