Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions enriched_activities.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,20 @@ func (a *EnrichedActivity) UnmarshalJSON(b []byte) error {
// MarshalJSON encodes the EnrichedActivity to a valid JSON bytes slice. It's required because of
// the custom JSON fields and time formats.
func (a EnrichedActivity) MarshalJSON() ([]byte, error) {
fields := structs.New(a).Fields()
data := make(map[string]interface{}, len(fields))
s := structs.New(a)
fields := s.Fields()
data := s.Map()
for _, f := range fields {
if f.Kind() == reflect.Struct {
tag := f.Tag("json")
if !strings.HasSuffix(tag, ",omitempty") || !structs.IsZero(f.Value()) {
data[strings.TrimSuffix(tag, ",omitempty")] = f.Value()
}
tag := f.Tag("json")
root := strings.TrimSuffix(tag, ",omitempty")

if f.Kind() != reflect.Struct ||
(strings.HasSuffix(tag, ",omitempty") &&
structs.IsZero(f.Value())) {
continue
}

data[root] = f.Value()
}
for k, v := range a.Extra {
data[k] = v
Expand Down
6 changes: 5 additions & 1 deletion types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,13 @@ func TestEnrichedActivityMarshal(t *testing.T) {
ID: "my_id",
Extra: map[string]interface{}{"a": 1, "b": "c"},
},
ReactionCounts: map[string]int{
"comment": 1,
},
Score: 100.0,
}

b, err := json.Marshal(e)
require.NoError(t, err)
require.JSONEq(t, `{"actor": {"id":"my_id","data":{"a":1,"b":"c"}}}`, string(b))
require.JSONEq(t, `{"actor": {"id":"my_id","data":{"a":1,"b":"c"}},"reaction_counts":{"comment":1},"score":100.0}`, string(b))
}