瀏覽代碼

Let UUID implements Marshaling interface for encoding/json

Kasper Middelboe Petersen 11 年之前
父節點
當前提交
d81fa727f6
共有 2 個文件被更改,包括 14 次插入0 次删除
  1. 5 0
      uuid.go
  2. 9 0
      uuid_test.go

+ 5 - 0
uuid.go

@@ -208,3 +208,8 @@ func (u UUID) Time() time.Time {
 	nsec := t % 1e7
 	return time.Unix(sec+timeBase, nsec).UTC()
 }
+
+// Marshaling for JSON
+func (u UUID) MarshalJSON() ([]byte, error) {
+	return []byte(`"` + u.String() + `"`), nil
+}

+ 9 - 0
uuid_test.go

@@ -59,6 +59,15 @@ func TestPredefinedUUID(t *testing.T) {
 				t.Errorf("Version #%d: expected %d got %d", i, testsUUID[i].version, version)
 			}
 		}
+
+		json, err := uuid.MarshalJSON()
+		if err != nil {
+			t.Errorf("MarshalJSON #%d: %v", i, err)
+		}
+		expectedJson := `"` + testsUUID[i].input + `"`
+		if string(json) != expectedJson {
+			t.Errorf("MarshalJSON #%d: expected %d got %d", i, expectedJson, string(json))
+		}
 	}
 }