Quellcode durchsuchen

Use MarshalJSON() of the wrapped Go value if available

Dmitry Panov vor 8 Jahren
Ursprung
Commit
8f3380f012
2 geänderte Dateien mit 21 neuen und 0 gelöschten Zeilen
  1. 7 0
      builtin_json.go
  2. 14 0
      builtin_json_test.go

+ 7 - 0
builtin_json.go

@@ -311,6 +311,13 @@ func (ctx *_builtinJSON_stringifyContext) str(key Value, holder *Object) bool {
 		case *objectGoReflect:
 		case *objectGoReflect:
 			if o1.toJson != nil {
 			if o1.toJson != nil {
 				value = ctx.r.ToValue(o1.toJson())
 				value = ctx.r.ToValue(o1.toJson())
+			} else if v, ok := o1.origValue.Interface().(json.Marshaler); ok {
+				b, err := v.MarshalJSON()
+				if err != nil {
+					panic(err)
+				}
+				ctx.buf.Write(b)
+				return true
 			} else {
 			} else {
 				switch o1.className() {
 				switch o1.className() {
 				case classNumber:
 				case classNumber:

+ 14 - 0
builtin_json_test.go

@@ -4,6 +4,7 @@ import (
 	"encoding/json"
 	"encoding/json"
 	"strings"
 	"strings"
 	"testing"
 	"testing"
+	"time"
 )
 )
 
 
 func TestJSONMarshalObject(t *testing.T) {
 func TestJSONMarshalObject(t *testing.T) {
@@ -20,6 +21,19 @@ func TestJSONMarshalObject(t *testing.T) {
 	}
 	}
 }
 }
 
 
+func TestJSONMarshalGoDate(t *testing.T) {
+	vm := New()
+	o := vm.NewObject()
+	o.Set("test", time.Unix(86400, 0).UTC())
+	b, err := json.Marshal(o)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if string(b) != `{"test":"1970-01-02T00:00:00Z"}` {
+		t.Fatalf("Unexpected value: %s", b)
+	}
+}
+
 func TestJSONMarshalObjectCircular(t *testing.T) {
 func TestJSONMarshalObjectCircular(t *testing.T) {
 	vm := New()
 	vm := New()
 	o := vm.NewObject()
 	o := vm.NewObject()