You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Open-IM-Server/internal/utils/utils.go

50 lines
1.0 KiB

3 years ago
package utils
import (
"encoding/json"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
3 years ago
"reflect"
3 years ago
)
3 years ago
func JsonDataList(resp interface{}) []map[string]interface{} {
var list []proto.Message
if reflect.TypeOf(resp).Kind() == reflect.Slice {
s := reflect.ValueOf(resp)
for i := 0; i < s.Len(); i++ {
ele := s.Index(i)
list = append(list, ele.Interface().(proto.Message))
}
}
3 years ago
result := make([]map[string]interface{}, 0)
3 years ago
for _, v := range list {
3 years ago
m := ProtoToMap(v, false)
3 years ago
result = append(result, m)
}
return result
}
func JsonDataOne(pb proto.Message) map[string]interface{} {
return ProtoToMap(pb, false)
}
func ProtoToMap(pb proto.Message, idFix bool) map[string]interface{} {
marshaler := jsonpb.Marshaler{
OrigName: true,
EnumsAsInts: false,
3 years ago
EmitDefaults: false,
3 years ago
}
s, _ := marshaler.MarshalToString(pb)
out := make(map[string]interface{})
json.Unmarshal([]byte(s), &out)
if idFix {
if _, ok := out["id"]; ok {
out["_id"] = out["id"]
delete(out, "id")
}
}
return out
}