mirror of
https://github.com/zeromicro/go-zero.git
synced 2025-01-23 09:00:20 +08:00
feat: add method to jsonx (#2049)
This commit is contained in:
parent
f6f6ee5c8c
commit
48f7e01158
@ -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…
Reference in New Issue
Block a user