1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
23 Alphabet string `json:"alpha"`
32 // ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshalling with and
34 var ifaceNumAsFloat64 = map[string]interface{}{
37 "k3": []interface{}{float64(1), float64(2.0), float64(3e-3)},
38 "k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)},
41 var ifaceNumAsNumber = map[string]interface{}{
44 "k3": []interface{}{Number("1"), Number("2.0"), Number("3e-3")},
45 "k4": map[string]interface{}{"kk1": "s", "kk2": Number("2")},
52 var txType = reflect.TypeOf((*tx)(nil)).Elem()
54 // A type that can unmarshal itself.
56 type unmarshaler struct {
60 func (u *unmarshaler) UnmarshalJSON(b []byte) error {
61 *u = unmarshaler{true} // All we need to see that UnmarshalJson is called.
70 um0, um1 unmarshaler // target2 of unmarshaling
72 umtrue = unmarshaler{true}
73 umslice = []unmarshaler{{true}}
74 umslicep = new([]unmarshaler)
75 umstruct = ustruct{unmarshaler{true}}
78 // Test data structures for anonymous fields.
88 *Embed0b `json:"e,omitempty"` // treated as named
89 Embed0c `json:"-"` // ignored
91 Embed0p // has Point with X, Y, used
92 Embed0q // has Point with Z, used
96 Level1a int // overridden by Embed0a's Level1a with json tag
97 Level1b int // used because Embed0a's Level1b is renamed
98 Level1c int // used because Embed0a's Level1c is ignored
99 Level1d int // annihilated by Embed0a's Level1d
100 Level1e int `json:"x"` // annihilated by Embed0a.Level1e
103 type Embed0a struct {
104 Level1a int `json:"Level1a,omitempty"`
105 Level1b int `json:"LEVEL1B,omitempty"`
106 Level1c int `json:"-"`
107 Level1d int // annihilated by Embed0's Level1d
108 Level1f int `json:"x"` // annihilated by Embed0's Level1e
115 type Embed0p struct {
119 type Embed0q struct {
124 Loop1 int `json:",omitempty"`
125 Loop2 int `json:",omitempty"`
129 // From reflect test:
130 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
152 // From reflect test:
153 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
172 type unmarshalTest struct {
181 // Given "hello", the first match should win.
182 First int `json:"HELLO"`
183 Second int `json:"Hello"`
186 var unmarshalTests = []unmarshalTest{
188 {in: `true`, ptr: new(bool), out: true},
189 {in: `1`, ptr: new(int), out: 1},
190 {in: `1.2`, ptr: new(float64), out: 1.2},
191 {in: `-5`, ptr: new(int16), out: int16(-5)},
192 {in: `2`, ptr: new(Number), out: Number("2"), useNumber: true},
193 {in: `2`, ptr: new(Number), out: Number("2")},
194 {in: `2`, ptr: new(interface{}), out: float64(2.0)},
195 {in: `2`, ptr: new(interface{}), out: Number("2"), useNumber: true},
196 {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"},
197 {in: `"http:\/\/"`, ptr: new(string), out: "http://"},
198 {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"},
199 {in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"},
200 {in: "null", ptr: new(interface{}), out: nil},
201 {in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeOf("")}},
202 {in: `{"x": 1}`, ptr: new(tx), out: tx{}},
203 {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}},
204 {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true},
205 {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64},
206 {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsNumber, useNumber: true},
208 // raw values with whitespace
209 {in: "\n true ", ptr: new(bool), out: true},
210 {in: "\t 1 ", ptr: new(int), out: 1},
211 {in: "\r 1.2 ", ptr: new(float64), out: 1.2},
212 {in: "\t -5 \n", ptr: new(int16), out: int16(-5)},
213 {in: "\t \"a\\u1234\" \n", ptr: new(string), out: "a\u1234"},
216 {in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}},
218 {in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}},
219 {in: `{"alpha": "abc"}`, ptr: new(U), out: U{Alphabet: "abc"}},
220 {in: `{"alphabet": "xyz"}`, ptr: new(U), out: U{}},
223 {in: `{"X": "foo", "Y"}`, err: &SyntaxError{"invalid character '}' after object key", 17}},
224 {in: `[1, 2, 3+]`, err: &SyntaxError{"invalid character '+' after array element", 9}},
225 {in: `{"X":12x}`, err: &SyntaxError{"invalid character 'x' after object key:value pair", 8}, useNumber: true},
228 {in: "\x01 42", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
229 {in: " 42 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 5}},
230 {in: "\x01 true", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
231 {in: " false \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 8}},
232 {in: "\x01 1.2", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
233 {in: " 3.4 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 6}},
234 {in: "\x01 \"string\"", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
235 {in: " \"string\" \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 11}},
238 {in: `[1, 2, 3]`, ptr: new([3]int), out: [3]int{1, 2, 3}},
239 {in: `[1, 2, 3]`, ptr: new([1]int), out: [1]int{1}},
240 {in: `[1, 2, 3]`, ptr: new([5]int), out: [5]int{1, 2, 3, 0, 0}},
243 {in: allValueIndent, ptr: new(All), out: allValue},
244 {in: allValueCompact, ptr: new(All), out: allValue},
245 {in: allValueIndent, ptr: new(*All), out: &allValue},
246 {in: allValueCompact, ptr: new(*All), out: &allValue},
247 {in: pallValueIndent, ptr: new(All), out: pallValue},
248 {in: pallValueCompact, ptr: new(All), out: pallValue},
249 {in: pallValueIndent, ptr: new(*All), out: &pallValue},
250 {in: pallValueCompact, ptr: new(*All), out: &pallValue},
252 // unmarshal interface test
253 {in: `{"T":false}`, ptr: &um0, out: umtrue}, // use "false" so test will fail if custom unmarshaler is not called
254 {in: `{"T":false}`, ptr: &ump, out: &umtrue},
255 {in: `[{"T":false}]`, ptr: &umslice, out: umslice},
256 {in: `[{"T":false}]`, ptr: &umslicep, out: &umslice},
257 {in: `{"M":{"T":false}}`, ptr: &umstruct, out: umstruct},
303 Point: image.Point{X: 15, Y: 16},
313 out: Ambig{First: 1},
317 in: `{"X": 1,"Y":2}`,
319 out: S5{S8: S8{S9: S9{Y: 2}}},
322 in: `{"X": 1,"Y":2}`,
324 out: S10{S13: S13{S8: S8{S9: S9{Y: 2}}}},
328 func TestMarshal(t *testing.T) {
329 b, err := Marshal(allValue)
331 t.Fatalf("Marshal allValue: %v", err)
333 if string(b) != allValueCompact {
334 t.Errorf("Marshal allValueCompact")
335 diff(t, b, []byte(allValueCompact))
339 b, err = Marshal(pallValue)
341 t.Fatalf("Marshal pallValue: %v", err)
343 if string(b) != pallValueCompact {
344 t.Errorf("Marshal pallValueCompact")
345 diff(t, b, []byte(pallValueCompact))
350 func TestMarshalBadUTF8(t *testing.T) {
351 s := "hello\xffworld"
354 t.Fatal("Marshal bad UTF8: no error")
357 t.Fatal("Marshal returned data")
359 if _, ok := err.(*InvalidUTF8Error); !ok {
360 t.Fatalf("Marshal did not return InvalidUTF8Error: %T %v", err, err)
364 func TestMarshalNumberZeroVal(t *testing.T) {
366 out, err := Marshal(n)
370 outStr := string(out)
372 t.Fatalf("Invalid zero val for Number: %q", outStr)
376 func TestUnmarshal(t *testing.T) {
377 for i, tt := range unmarshalTests {
380 if err := checkValid(in, &scan); err != nil {
381 if !reflect.DeepEqual(err, tt.err) {
382 t.Errorf("#%d: checkValid: %#v", i, err)
389 // v = new(right-type)
390 v := reflect.New(reflect.TypeOf(tt.ptr).Elem())
391 dec := NewDecoder(bytes.NewBuffer(in))
395 if err := dec.Decode(v.Interface()); !reflect.DeepEqual(err, tt.err) {
396 t.Errorf("#%d: %v want %v", i, err, tt.err)
399 if !reflect.DeepEqual(v.Elem().Interface(), tt.out) {
400 t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out)
401 data, _ := Marshal(v.Elem().Interface())
402 println(string(data))
403 data, _ = Marshal(tt.out)
404 println(string(data))
410 enc, err := Marshal(v.Interface())
412 t.Errorf("#%d: error re-marshaling: %v", i, err)
415 vv := reflect.New(reflect.TypeOf(tt.ptr).Elem())
416 dec = NewDecoder(bytes.NewBuffer(enc))
420 if err := dec.Decode(vv.Interface()); err != nil {
421 t.Errorf("#%d: error re-unmarshaling: %v", i, err)
424 if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) {
425 t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface())
432 func TestUnmarshalMarshal(t *testing.T) {
435 if err := Unmarshal(jsonBig, &v); err != nil {
436 t.Fatalf("Unmarshal: %v", err)
440 t.Fatalf("Marshal: %v", err)
442 if !bytes.Equal(jsonBig, b) {
443 t.Errorf("Marshal jsonBig")
449 var numberTests = []struct {
456 {in: "-1.23e1", intErr: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f: -1.23e1},
457 {in: "-12", i: -12, f: -12.0},
458 {in: "1e1000", intErr: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr: "strconv.ParseFloat: parsing \"1e1000\": value out of range"},
461 // Independent of Decode, basic coverage of the accessors in Number
462 func TestNumberAccessors(t *testing.T) {
463 for _, tt := range numberTests {
465 if s := n.String(); s != tt.in {
466 t.Errorf("Number(%q).String() is %q", tt.in, s)
468 if i, err := n.Int64(); err == nil && tt.intErr == "" && i != tt.i {
469 t.Errorf("Number(%q).Int64() is %d", tt.in, i)
470 } else if (err == nil && tt.intErr != "") || (err != nil && err.Error() != tt.intErr) {
471 t.Errorf("Number(%q).Int64() wanted error %q but got: %v", tt.in, tt.intErr, err)
473 if f, err := n.Float64(); err == nil && tt.floatErr == "" && f != tt.f {
474 t.Errorf("Number(%q).Float64() is %g", tt.in, f)
475 } else if (err == nil && tt.floatErr != "") || (err != nil && err.Error() != tt.floatErr) {
476 t.Errorf("Number(%q).Float64() wanted error %q but got: %v", tt.in, tt.floatErr, err)
481 func TestLargeByteSlice(t *testing.T) {
482 s0 := make([]byte, 2000)
486 b, err := Marshal(s0)
488 t.Fatalf("Marshal: %v", err)
491 if err := Unmarshal(b, &s1); err != nil {
492 t.Fatalf("Unmarshal: %v", err)
494 if !bytes.Equal(s0, s1) {
495 t.Errorf("Marshal large byte slice")
504 func TestUnmarshalInterface(t *testing.T) {
506 var i interface{} = &xint
507 if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil {
508 t.Fatalf("Unmarshal: %v", err)
511 t.Fatalf("Did not write to xint")
515 func TestUnmarshalPtrPtr(t *testing.T) {
518 if err := Unmarshal([]byte(`{"X":1}`), &pxint); err != nil {
519 t.Fatalf("Unmarshal: %v", err)
522 t.Fatalf("Did not write to xint")
526 func TestEscape(t *testing.T) {
527 const input = `"foobar"<html>`
528 const expected = `"\"foobar\"\u003chtml\u003e"`
529 b, err := Marshal(input)
531 t.Fatalf("Marshal error: %v", err)
533 if s := string(b); s != expected {
534 t.Errorf("Encoding of [%s] was [%s], want [%s]", input, s, expected)
538 // WrongString is a struct that's misusing the ,string modifier.
539 type WrongString struct {
540 Message string `json:"result,string"`
543 type wrongStringTest struct {
547 var wrongStringTests = []wrongStringTest{
548 {`{"result":"x"}`, `json: invalid use of ,string struct tag, trying to unmarshal "x" into string`},
549 {`{"result":"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "foo" into string`},
550 {`{"result":"123"}`, `json: invalid use of ,string struct tag, trying to unmarshal "123" into string`},
553 // If people misuse the ,string modifier, the error message should be
554 // helpful, telling the user that they're doing it wrong.
555 func TestErrorMessageFromMisusedString(t *testing.T) {
556 for n, tt := range wrongStringTests {
557 r := strings.NewReader(tt.in)
559 err := NewDecoder(r).Decode(&s)
560 got := fmt.Sprintf("%v", err)
562 t.Errorf("%d. got err = %q, want %q", n, got, tt.err)
567 func noSpace(c rune) rune {
590 Foo string `json:"bar"`
591 Foo2 string `json:"bar2,dummyopt"`
593 IntStr int64 `json:",string"`
614 MapP map[string]*Small
615 PMap *map[string]Small
616 PMapP *map[string]*Small
618 EmptyMap map[string]Small
619 NilMap map[string]Small
636 Interface interface{}
637 PInterface *interface{}
665 Map: map[string]Small{
666 "17": {Tag: "tag17"},
667 "18": {Tag: "tag18"},
669 MapP: map[string]*Small{
670 "19": {Tag: "tag19"},
673 EmptyMap: map[string]Small{},
674 Slice: []Small{{Tag: "tag20"}, {Tag: "tag21"}},
675 SliceP: []*Small{{Tag: "tag22"}, nil, {Tag: "tag23"}},
676 EmptySlice: []Small{},
677 StringSlice: []string{"str24", "str25", "str26"},
678 ByteSlice: []byte{27, 28, 29},
679 Small: Small{Tag: "tag30"},
680 PSmall: &Small{Tag: "tag31"},
685 PBool: &allValue.Bool,
687 PInt8: &allValue.Int8,
688 PInt16: &allValue.Int16,
689 PInt32: &allValue.Int32,
690 PInt64: &allValue.Int64,
691 PUint: &allValue.Uint,
692 PUint8: &allValue.Uint8,
693 PUint16: &allValue.Uint16,
694 PUint32: &allValue.Uint32,
695 PUint64: &allValue.Uint64,
696 PUintptr: &allValue.Uintptr,
697 PFloat32: &allValue.Float32,
698 PFloat64: &allValue.Float64,
699 PString: &allValue.String,
701 PMapP: &allValue.MapP,
702 PSlice: &allValue.Slice,
703 PSliceP: &allValue.SliceP,
704 PPSmall: &allValue.PSmall,
705 PInterface: &allValue.Interface,
708 var allValueIndent = `{
798 var allValueCompact = strings.Map(noSpace, allValueIndent)
800 var pallValueIndent = `{
886 var pallValueCompact = strings.Map(noSpace, pallValueIndent)
888 func TestRefUnmarshal(t *testing.T) {
890 // Ref is defined in encode_test.go.
901 if err := Unmarshal([]byte(`{"R0":"ref","R1":"ref"}`), &got); err != nil {
902 t.Fatalf("Unmarshal: %v", err)
904 if !reflect.DeepEqual(got, want) {
905 t.Errorf("got %+v, want %+v", got, want)
909 // Test that the empty string doesn't panic decoding when ,string is specified
911 func TestEmptyString(t *testing.T) {
913 Number1 int `json:",string"`
914 Number2 int `json:",string"`
916 data := `{"Number1":"1", "Number2":""}`
917 dec := NewDecoder(strings.NewReader(data))
919 err := dec.Decode(&t2)
921 t.Fatal("Decode: did not return error")
924 t.Fatal("Decode: did not set Number1")
928 func intp(x int) *int {
934 func intpp(x *int) **int {
940 var interfaceSetTests = []struct {
945 {"foo", `"bar"`, "bar"},
947 {"foo", `true`, true},
948 {"foo", `null`, nil},
951 {new(int), `null`, nil},
952 {(*int)(nil), `null`, nil},
953 {new(*int), `null`, new(*int)},
954 {(**int)(nil), `null`, nil},
955 {intp(1), `null`, nil},
956 {intpp(nil), `null`, intpp(nil)},
957 {intpp(intp(1)), `null`, intpp(nil)},
960 func TestInterfaceSet(t *testing.T) {
961 for _, tt := range interfaceSetTests {
962 b := struct{ X interface{} }{tt.pre}
963 blob := `{"X":` + tt.json + `}`
964 if err := Unmarshal([]byte(blob), &b); err != nil {
965 t.Errorf("Unmarshal %#q: %v", blob, err)
968 if !reflect.DeepEqual(b.X, tt.post) {
969 t.Errorf("Unmarshal %#q into %#v: X=%#v, want %#v", blob, tt.pre, b.X, tt.post)
974 // JSON null values should be ignored for primitives and string values instead of resulting in an error.
976 func TestUnmarshalNulls(t *testing.T) {
977 jsonData := []byte(`{
1009 err := Unmarshal(jsonData, &nulls)
1011 t.Errorf("Unmarshal of null values failed: %v", err)
1013 if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 ||
1014 nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 ||
1015 nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" {
1017 t.Errorf("Unmarshal of null values affected primitives")
1021 func TestStringKind(t *testing.T) {
1022 type stringKind string
1023 type aMap map[stringKind]int
1025 var m1, m2 map[stringKind]int
1026 m1 = map[stringKind]int{
1030 data, err := Marshal(m1)
1032 t.Errorf("Unexpected error marshalling: %v", err)
1035 err = Unmarshal(data, &m2)
1037 t.Errorf("Unexpected error unmarshalling: %v", err)
1040 if !reflect.DeepEqual(m1, m2) {
1041 t.Error("Items should be equal after encoding and then decoding")
1046 var decodeTypeErrorTests = []struct {
1050 {new(string), `{"user": "name"}`}, // issue 4628.
1051 {new(error), `{}`}, // issue 4222
1054 {new(error), `123`},
1055 {new(error), `true`},
1058 func TestUnmarshalTypeError(t *testing.T) {
1059 for _, item := range decodeTypeErrorTests {
1060 err := Unmarshal([]byte(item.src), item.dest)
1061 if _, ok := err.(*UnmarshalTypeError); !ok {
1062 t.Errorf("expected type error for Unmarshal(%q, type %T): got %T",
1063 item.src, item.dest, err)
1068 var unmarshalSyntaxTests = []string{
1079 func TestUnmarshalSyntax(t *testing.T) {
1081 for _, src := range unmarshalSyntaxTests {
1082 err := Unmarshal([]byte(src), &x)
1083 if _, ok := err.(*SyntaxError); !ok {
1084 t.Errorf("expected syntax error for Unmarshal(%q): got %T", src, err)
1089 // Test handling of unexported fields that should be ignored.
1091 type unexportedFields struct {
1093 m map[string]interface{} `json:"-"`
1094 m2 map[string]interface{} `json:"abcd"`
1097 func TestUnmarshalUnexported(t *testing.T) {
1098 input := `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}}`
1099 want := &unexportedFields{Name: "Bob"}
1101 out := &unexportedFields{}
1102 err := Unmarshal([]byte(input), out)
1104 t.Errorf("got error %v, expected nil", err)
1106 if !reflect.DeepEqual(out, want) {
1107 t.Errorf("got %q, want %q", out, want)