@ -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
@ -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)