jeudi 29 juillet 2021

How to convert map[interface{}]interface{} to map[string]string with reflection

I have a struct

type ClientSubscriptions struct {
    ID         int64
    Service    string
    Identifier string
    EventType  string
    DateBegin  *time.Time
    DateEnd    *time.Time
    Extra      map[string]string
}

and i have an origin source which send me some data. I have no problems with parsing such types as int64, string and time. But i can't convert json object Extra to my struct

func parseSubscription(data []interface{}) (*ClientSubscriptions, error) {
    if len(data) == 0 {
        return nil, nil
    }

    res := ClientSubscriptions{}
    values := reflect.ValueOf(&res).Elem()
    controlTupleSize := values.NumField()

    if len(data) < controlTupleSize {
        return nil,
            fmt.Errorf("unexpected control tuple size %d, want %d", len(data), controlTupleSize)
    }

    for i, v := range data {
        value := values.Field(i)
        switch value.Interface().(type) {
        case int64:
            val, err := utils.ParseToInt64(v)
            if err != nil {
                return nil, err
            }
            value.SetInt(val)
        case *time.Time:
            val := v.(uint64)
            date := time.Unix(int64(val), 0)
            value.Set(reflect.ValueOf(&date))
        case string:
            val := v.(string)
            value.SetString(val)
        case interface{}:
            val := v.(map[string]interface{})
            if len(val) > 0 {
                for key, info := range val {
                    strKey := fmt.Sprintf("%v", key)
                    strValue := fmt.Sprintf("%v", info)
                    value.SetMapIndex(reflect.ValueOf(strKey), reflect.ValueOf(strValue))
                }
            }
        }

    }

    return &res, nil
}

panic: assignment to entry in nil map





Aucun commentaire:

Enregistrer un commentaire