func support json serialize

This commit is contained in:
liushaobo 2021-03-12 22:58:54 +08:00
parent 8d17101741
commit ab1c95bdd4
2 changed files with 27 additions and 2 deletions

View File

@ -7,6 +7,7 @@ package cast
import (
"errors"
"encoding/json"
"fmt"
"html/template"
"testing"
@ -599,6 +600,19 @@ func TestToStringE(t *testing.T) {
}
key := &Key{"foo"}
type Stru struct {
K string
}
stru := &Stru{K:"foo"}
struStr, _ := json.Marshal(stru)
dic := map[string]interface{}{
"obj": map[string]int{"key": 123},
}
dicStr, _ := json.Marshal(dic)
tests := []struct {
input interface{}
expect string
@ -620,15 +634,19 @@ func TestToStringE(t *testing.T) {
{false, "false", false},
{nil, "", false},
{[]byte("one time"), "one time", false},
{[]byte("你好!"), "你好!", false},
{[]rune("你好!"), "你好!", false},
{"one more time", "one more time", false},
{template.HTML("one time"), "one time", false},
{template.URL("http://somehost.foo"), "http://somehost.foo", false},
{template.JS("(1+2)"), "(1+2)", false},
{template.CSS("a"), "a", false},
{template.HTMLAttr("a"), "a", false},
{dic, string(dicStr), false},
{stru, string(struStr), false},
// errors
{testing.T{}, "", true},
{key, "", true},
{testing.T{}, "{}", false},
{key, "{}", false},
}
for i, test := range tests {

View File

@ -830,6 +830,8 @@ func ToStringE(i interface{}) (string, error) {
return strconv.FormatUint(uint64(s), 10), nil
case []byte:
return string(s), nil
case []rune:
return string(s), nil
case template.HTML:
return string(s), nil
case template.URL:
@ -847,6 +849,11 @@ func ToStringE(i interface{}) (string, error) {
case error:
return s.Error(), nil
default:
jsonContent, err := json.Marshal(s)
if err == nil {
return string(jsonContent), nil
}
return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
}
}