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.
66 lines
1.3 KiB
66 lines
1.3 KiB
2 years ago
|
package xjson
|
||
2 years ago
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
2 years ago
|
"fmt"
|
||
2 years ago
|
"google.golang.org/protobuf/encoding/protojson"
|
||
|
"google.golang.org/protobuf/proto"
|
||
|
"reflect"
|
||
|
)
|
||
|
|
||
2 years ago
|
func MustMarshal(data any) string {
|
||
|
b, err := json.Marshal(data)
|
||
|
if err != nil {
|
||
|
return ""
|
||
|
}
|
||
|
return string(b)
|
||
|
}
|
||
|
|
||
2 years ago
|
var (
|
||
|
// MarshalOptions is a configurable JSON format marshaller.
|
||
|
MarshalOptions = protojson.MarshalOptions{
|
||
|
EmitUnpopulated: true,
|
||
|
}
|
||
|
// UnmarshalOptions is a configurable JSON format parser.
|
||
|
UnmarshalOptions = protojson.UnmarshalOptions{
|
||
|
DiscardUnknown: true,
|
||
|
}
|
||
|
)
|
||
|
|
||
2 years ago
|
func Marshal(v interface{}) ([]byte, error) {
|
||
2 years ago
|
switch m := v.(type) {
|
||
|
case json.Marshaler:
|
||
|
return m.MarshalJSON()
|
||
|
case proto.Message:
|
||
|
return MarshalOptions.Marshal(m)
|
||
|
default:
|
||
|
return json.Marshal(m)
|
||
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
func Unmarshal(data []byte, v interface{}) error {
|
||
2 years ago
|
switch m := v.(type) {
|
||
|
case json.Unmarshaler:
|
||
|
return m.UnmarshalJSON(data)
|
||
|
case proto.Message:
|
||
|
return UnmarshalOptions.Unmarshal(data, m)
|
||
|
default:
|
||
|
rv := reflect.ValueOf(v)
|
||
|
for rv := rv; rv.Kind() == reflect.Ptr; {
|
||
|
if rv.IsNil() {
|
||
|
rv.Set(reflect.New(rv.Type().Elem()))
|
||
|
}
|
||
|
rv = rv.Elem()
|
||
|
}
|
||
|
if m, ok := reflect.Indirect(rv).Interface().(proto.Message); ok {
|
||
|
return UnmarshalOptions.Unmarshal(data, m)
|
||
|
}
|
||
|
return json.Unmarshal(data, m)
|
||
|
}
|
||
|
}
|
||
2 years ago
|
|
||
|
func PrintData(a any) {
|
||
|
b, _ := Marshal(a)
|
||
|
fmt.Println(string(b))
|
||
|
}
|