using go, how do i turn a map[int]T to a map[string]T to use with JSON? -


my code getting plastered functions following:

func transformmapclassa(mapofinttoclassa map[int]*classa) map[string]*classa {   mapofstringtoclassa := make(map[string]*classa)   id, obj := range mapofinttoclassa {     mapofstringtoclassa[fmt.sprintf("%d" obj.id)] = obj   }   return mapofstringtoclassa } 

written once each class in application. i'm doing this, can json.marshal existing map. there generic way of doing this, don't have write 1 function per class? i've tried doing things like:

type int64json int64 `json:",string"` 

and using int64json in original maps, compiler doesn't json tag in type definition :(

many in advance!

if still want use reflection create function returns map[string]interface{} type of map, can 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()     _, k := range keys {         result[fmt.sprint(k.interface())] = v.mapindex(k).interface()     }      return result, nil } 

playground


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -