How to unmarshal map of struct?
added a map[string]
of Person
type to redis using
conn.Do("HMSET", redis.Args{"Teams"}.AddFlat(values)...);
I am able to print a value
v, err := redis.String(conn.Do("HGET", key, field))
log.Print(v)
succesfully prints the value, but how can I unmarshal it back to struct of type Person
?
How I added
m:= make(map[string]Person)
m['E21']=Person{"FirstName","LastName"}
HMSet("Team", m)
How I added to redis
func HMSet(key string, values map[string]dataobjects.Person) error {
conn := Pool.Get()
defer conn.Close()
if _, err := conn.Do("HMSET", redis.Args{key}.AddFlat(values)...); err != nil {
log.Fatal(err)
}
return nil
}
How I got it back
func HGet(key, field string) error {
conn := Pool.Get()
defer conn.Close()
v, err := redis.Bytes(conn.Do("HGET", key, field))
if err != nil {
fmt.Println(err)
return err
}
// I am able to print v succesfully,but how to return Person object from v
return nil
}
My struct
type Person struct {
FirstName string `FirstName `
LastName string `LastName `
}
func marshal(in interface{}) []byte {
var buf bytes.Buffer
encoder := gob.NewEncoder(&buf)
err := encoder.Encode(in)
assert.Nil(err)
return buf.Bytes()
}
func unmarshal(data []byte) Person {
buffer := bytes.NewBuffer(data)
decoder := gob.NewDecoder(buffer)
var p Person
err := decoder.Decode(p)
assert.Nil(err)
return p
}
you can use these to marshal your structs, swap person with your map, also make sure your struct has struct tags and capitalized first character of each field