diff --git a/serializer/jsonSerializer.go b/serializer/jsonSerializer.go index cddefd9d..fd8ed838 100644 --- a/serializer/jsonSerializer.go +++ b/serializer/jsonSerializer.go @@ -2,8 +2,10 @@ package serializer import ( "bytes" + "encoding/json" "errors" "io" + "sort" "strconv" "time" @@ -59,6 +61,32 @@ func (serializer JSONSerializer) ReaderToPayload(r io.Reader) moleculer.Payload return payload } +//MapToString serialize a map into a string +//This implementation uses the standard library json pkg and it needs to be compared with others for performance. +//Performance: it should be experimented with multiple implementations. This is just he initial one. +func (serializer JSONSerializer) MapToString(m interface{}) string { + r, err := json.Marshal(m) + if err != nil { + serializer.logger.Errorln("Error trying to serialize a map. error: ", err) + panic(err) + } + s := string(r) + return s +} + +//StringToMap deserialize a string (json) into map +//Same implementation and performance notes as MapToString +func (serializer JSONSerializer) StringToMap(j string) map[string]interface{} { + m := map[string]interface{}{} + err := json.Unmarshal([]byte(j), &m) + if err != nil { + serializer.logger.Errorln("Error trying to deserialize a map from json: " + j) + serializer.logger.Errorln("error: ", err) + panic(err) + } + return m +} + func (serializer JSONSerializer) PayloadToBytes(payload moleculer.Payload) []byte { return []byte(serializer.PayloadToString(payload)) } diff --git a/serializer/serializer.go b/serializer/serializer.go index 186d707f..ae0c0eca 100644 --- a/serializer/serializer.go +++ b/serializer/serializer.go @@ -1,8 +1,9 @@ package serializer import ( - "github.com/moleculer-go/moleculer" "io" + + "github.com/moleculer-go/moleculer" ) type Serializer interface { @@ -10,6 +11,8 @@ type Serializer interface { BytesToPayload(*[]byte) moleculer.Payload PayloadToBytes(moleculer.Payload) []byte PayloadToString(moleculer.Payload) string + MapToString(interface{}) string + StringToMap(string) map[string]interface{} PayloadToContextMap(moleculer.Payload) map[string]interface{} MapToPayload(*map[string]interface{}) (moleculer.Payload, error) }