diff --git a/core/jsonx/json.go b/core/jsonx/json.go index 176e30a0..34cf92ea 100644 --- a/core/jsonx/json.go +++ b/core/jsonx/json.go @@ -53,3 +53,12 @@ func unmarshalUseNumber(decoder *json.Decoder, v interface{}) error { func formatError(v string, err error) error { return fmt.Errorf("string: `%s`, error: `%w`", v, err) } + +// MarshalToString marshals v into string. +func MarshalToString(v interface{}) (string, error) { + data, err := Marshal(v) + if err != nil { + return "", formatError(string(data), err) + } + return string(data), nil +} diff --git a/core/jsonx/json_test.go b/core/jsonx/json_test.go index 48221e36..d11ce992 100644 --- a/core/jsonx/json_test.go +++ b/core/jsonx/json_test.go @@ -85,3 +85,16 @@ func TestUnmarshalFromReaderError(t *testing.T) { err := UnmarshalFromReader(strings.NewReader(s), &v) assert.NotNil(t, err) } + +func TestMarshalToString(t *testing.T) { + var v = struct { + Name string `json:"name"` + Age int `json:"age"` + }{ + Name: "John", + Age: 30, + } + toString, err := MarshalToString(v) + assert.Nil(t, err) + assert.Equal(t, `{"name":"John","age":30}`, toString) +}