dtnnpt11795 2013-09-16 05:40
浏览 39
已采纳

映射<->结构类型转换

Currently this is the method I use to convert map[string]interface{} to 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
}

I found json package to hack my way through this, but what is the right way to do this conversion? obviously without using json package

  • 写回答

1条回答 默认 最新

  • dongnao6858 2013-09-16 06:06
    关注

    The encoding/json package makes use of the reflect package to marshal and unmarshal messages.

    So you can do the same with reflect directly. If you don't need the support for nested structs and arrays, the following should do the trick:

    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))
    }
    

    You can experiment further with this code in the playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算