目前这是我用来将 map[string]interface{} 转换为 Message struct 的方法
byteBlob, err := json.Marshal(messageMap)
if err != nil {
return nil, err
}
message := &Message{}
err = json.Unmarshal(byteBlob, message)
if err != nil {
return nil, err
}
我发现 json 包可以解决这个问题,但是进行这种转换的正确方法是什么?显然没有使用 json 包
最佳答案
encoding/json
包使用reflect
包来编码和解码消息。
所以你可以直接用 reflect
做同样的事情。如果您不需要对嵌套结构和数组的支持,那么以下应该可以解决问题:
message := Message{}
v := reflect.ValueOf(&message).Elem()
for key, value := range messageMap {
field := v.FieldByName(key)
if !field.IsValid() {
// or handle as error if you don't expect unknown values
continue
}
if !field.CanSet() {
// or return an error on private fields
continue
}
field.Set(reflect.ValueOf(value))
}
您可以使用此代码进一步试验 in the playground .
关于go - 映射 <-> 结构类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18821038/