Skip to content

Commit bb3fc02

Browse files
Assign values of type Map in deep objects (#934)
* Assign values of type Map in deep objects * Ensure map value type conversion --------- Co-authored-by: Luis Rodrigues <lrodrigues@newstore.com>
1 parent a1d3ca2 commit bb3fc02

File tree

2 files changed

+32
-12
lines changed

2 files changed

+32
-12
lines changed

deepobject.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,19 @@ func assignPathValues(dst interface{}, pathValues fieldOrValue) error {
200200
it := iv.Type()
201201

202202
switch it.Kind() {
203+
case reflect.Map:
204+
dstMap := reflect.MakeMap(iv.Type())
205+
for key, value := range pathValues.fields {
206+
dstKey := reflect.ValueOf(key)
207+
dstVal := reflect.New(iv.Type().Elem())
208+
err := assignPathValues(dstVal.Interface(), value)
209+
if err != nil {
210+
return fmt.Errorf("error binding map: %w", err)
211+
}
212+
dstMap.SetMapIndex(dstKey, dstVal.Elem())
213+
}
214+
iv.Set(dstMap)
215+
return nil
203216
case reflect.Slice:
204217
sliceLength := len(pathValues.fields)
205218
dstSlice := reflect.MakeSlice(it, sliceLength, sliceLength)

deepobject_test.go

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,20 @@ type InnerObject struct {
1717

1818
// These are all possible field types, mandatory and optional.
1919
type AllFields struct {
20-
I int `json:"i"`
21-
Oi *int `json:"oi,omitempty"`
22-
F float32 `json:"f"`
23-
Of *float32 `json:"of,omitempty"`
24-
B bool `json:"b"`
25-
Ob *bool `json:"ob,omitempty"`
26-
As []string `json:"as"`
27-
Oas *[]string `json:"oas,omitempty"`
28-
O InnerObject `json:"o"`
29-
Oo *InnerObject `json:"oo,omitempty"`
30-
D MockBinder `json:"d"`
31-
Od *MockBinder `json:"od,omitempty"`
20+
I int `json:"i"`
21+
Oi *int `json:"oi,omitempty"`
22+
F float32 `json:"f"`
23+
Of *float32 `json:"of,omitempty"`
24+
B bool `json:"b"`
25+
Ob *bool `json:"ob,omitempty"`
26+
As []string `json:"as"`
27+
Oas *[]string `json:"oas,omitempty"`
28+
O InnerObject `json:"o"`
29+
Oo *InnerObject `json:"oo,omitempty"`
30+
D MockBinder `json:"d"`
31+
Od *MockBinder `json:"od,omitempty"`
32+
M map[string]int `json:"m"`
33+
Om *map[string]int `json:"om,omitempty"`
3234
}
3335

3436
func TestDeepObject(t *testing.T) {
@@ -40,6 +42,9 @@ func TestDeepObject(t *testing.T) {
4042
Name: "Marcin Romaszewicz",
4143
ID: 123,
4244
}
45+
om := map[string]int{
46+
"additional": 1,
47+
}
4348
d := MockBinder{Time: time.Date(2020, 2, 1, 0, 0, 0, 0, time.UTC)}
4449

4550
srcObj := AllFields{
@@ -58,6 +63,8 @@ func TestDeepObject(t *testing.T) {
5863
Oo: &oo,
5964
D: d,
6065
Od: &d,
66+
M: om,
67+
Om: &om,
6168
}
6269

6370
marshaled, err := MarshalDeepObject(srcObj, "p")

0 commit comments

Comments
 (0)