feat: add method to jsonx (#2049)

master
Minghong Fang 2 years ago committed by GitHub
parent f6f6ee5c8c
commit 48f7e01158
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

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

Loading…
Cancel
Save