duanou2016 2013-09-24 15:51
浏览 111
已采纳

使用go,如何将map [int] T转换为map [string] T以与JSON一起使用?

My code is getting plastered with functions like the following:

func TransformMapClassA(mapOfIntToClassA map[int]*ClassA) map[string]*ClassA {
  mapOfStringToClassA := make(map[string]*ClassA)
  for id, obj := range mapOfIntToClassA {
    mapOfStringToClassA[fmt.Sprintf("%d" obj.Id)] = obj
  }
  return mapOfStringToClassA
}

written once for each class in my application. I'm doing this, so I can json.Marshal the existing map. Is there a generic way of doing this, so I don't have to write one function per class? I've tried doing things like:

type Int64JSON int64 `json:",string"`

and using Int64JSON in my original maps, but the compiler doesn't like the json tag in a type definition :(

Many thanks in advance!

  • 写回答

2条回答 默认 最新

  • dpw5865 2013-09-25 13:35
    关注

    If you still want to use reflection to create a function that returns a map[string]interface{} from any type of map, you can do the following:

    func TransformMap(m interface{}) (map[string]interface{}, error) {
    
        v := reflect.ValueOf(m)
    
        if v.Kind() != reflect.Map {
            return nil, errors.New("Map required")
        }
    
        result := make(map[string]interface{}, v.Len())
    
        keys := v.MapKeys()
        for _, k := range keys {
            result[fmt.Sprint(k.Interface())] = v.MapIndex(k).Interface()
        }
    
        return result, nil
    }
    

    Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用