github.com/night-codes/go-json@v0.9.15/decode_test.go (about) 1 package json_test 2 3 import ( 4 "bytes" 5 "context" 6 "encoding" 7 stdjson "encoding/json" 8 "errors" 9 "fmt" 10 "image" 11 "math" 12 "math/big" 13 "net" 14 "reflect" 15 "strconv" 16 "strings" 17 "testing" 18 "time" 19 "unsafe" 20 21 "github.com/night-codes/go-json" 22 ) 23 24 func Test_Decoder(t *testing.T) { 25 t.Run("int", func(t *testing.T) { 26 var v int 27 assertErr(t, json.Unmarshal([]byte(`-1`), &v)) 28 assertEq(t, "int", int(-1), v) 29 }) 30 t.Run("int8", func(t *testing.T) { 31 var v int8 32 assertErr(t, json.Unmarshal([]byte(`-2`), &v)) 33 assertEq(t, "int8", int8(-2), v) 34 }) 35 t.Run("int16", func(t *testing.T) { 36 var v int16 37 assertErr(t, json.Unmarshal([]byte(`-3`), &v)) 38 assertEq(t, "int16", int16(-3), v) 39 }) 40 t.Run("int32", func(t *testing.T) { 41 var v int32 42 assertErr(t, json.Unmarshal([]byte(`-4`), &v)) 43 assertEq(t, "int32", int32(-4), v) 44 }) 45 t.Run("int64", func(t *testing.T) { 46 var v int64 47 assertErr(t, json.Unmarshal([]byte(`-5`), &v)) 48 assertEq(t, "int64", int64(-5), v) 49 }) 50 t.Run("uint", func(t *testing.T) { 51 var v uint 52 assertErr(t, json.Unmarshal([]byte(`1`), &v)) 53 assertEq(t, "uint", uint(1), v) 54 }) 55 t.Run("uint8", func(t *testing.T) { 56 var v uint8 57 assertErr(t, json.Unmarshal([]byte(`2`), &v)) 58 assertEq(t, "uint8", uint8(2), v) 59 }) 60 t.Run("uint16", func(t *testing.T) { 61 var v uint16 62 assertErr(t, json.Unmarshal([]byte(`3`), &v)) 63 assertEq(t, "uint16", uint16(3), v) 64 }) 65 t.Run("uint32", func(t *testing.T) { 66 var v uint32 67 assertErr(t, json.Unmarshal([]byte(`4`), &v)) 68 assertEq(t, "uint32", uint32(4), v) 69 }) 70 t.Run("uint64", func(t *testing.T) { 71 var v uint64 72 assertErr(t, json.Unmarshal([]byte(`5`), &v)) 73 assertEq(t, "uint64", uint64(5), v) 74 }) 75 t.Run("bool", func(t *testing.T) { 76 t.Run("true", func(t *testing.T) { 77 var v bool 78 assertErr(t, json.Unmarshal([]byte(`true`), &v)) 79 assertEq(t, "bool", true, v) 80 }) 81 t.Run("false", func(t *testing.T) { 82 v := true 83 assertErr(t, json.Unmarshal([]byte(`false`), &v)) 84 assertEq(t, "bool", false, v) 85 }) 86 }) 87 t.Run("string", func(t *testing.T) { 88 var v string 89 assertErr(t, json.Unmarshal([]byte(`"hello"`), &v)) 90 assertEq(t, "string", "hello", v) 91 }) 92 t.Run("float32", func(t *testing.T) { 93 var v float32 94 assertErr(t, json.Unmarshal([]byte(`3.14`), &v)) 95 assertEq(t, "float32", float32(3.14), v) 96 }) 97 t.Run("float64", func(t *testing.T) { 98 var v float64 99 assertErr(t, json.Unmarshal([]byte(`3.14`), &v)) 100 assertEq(t, "float64", float64(3.14), v) 101 }) 102 t.Run("slice", func(t *testing.T) { 103 var v []int 104 assertErr(t, json.Unmarshal([]byte(` [ 1 , 2 , 3 , 4 ] `), &v)) 105 assertEq(t, "slice", fmt.Sprint([]int{1, 2, 3, 4}), fmt.Sprint(v)) 106 }) 107 t.Run("slice_reuse_data", func(t *testing.T) { 108 v := make([]int, 0, 10) 109 assertErr(t, json.Unmarshal([]byte(` [ 1 , 2 , 3 , 4 ] `), &v)) 110 assertEq(t, "slice", fmt.Sprint([]int{1, 2, 3, 4}), fmt.Sprint(v)) 111 assertEq(t, "cap", 10, cap(v)) 112 }) 113 t.Run("array", func(t *testing.T) { 114 var v [4]int 115 assertErr(t, json.Unmarshal([]byte(` [ 1 , 2 , 3 , 4 ] `), &v)) 116 assertEq(t, "array", fmt.Sprint([4]int{1, 2, 3, 4}), fmt.Sprint(v)) 117 }) 118 t.Run("map", func(t *testing.T) { 119 var v map[string]int 120 assertErr(t, json.Unmarshal([]byte(` { "a": 1, "b": 2, "c": 3, "d": 4 } `), &v)) 121 assertEq(t, "map.a", v["a"], 1) 122 assertEq(t, "map.b", v["b"], 2) 123 assertEq(t, "map.c", v["c"], 3) 124 assertEq(t, "map.d", v["d"], 4) 125 t.Run("nested map", func(t *testing.T) { 126 // https://github.com/night-codes/go-json/issues/8 127 content := ` 128 { 129 "a": { 130 "nestedA": "value of nested a" 131 }, 132 "b": { 133 "nestedB": "value of nested b" 134 }, 135 "c": { 136 "nestedC": "value of nested c" 137 } 138 }` 139 var v map[string]interface{} 140 assertErr(t, json.Unmarshal([]byte(content), &v)) 141 assertEq(t, "length", 3, len(v)) 142 }) 143 }) 144 t.Run("struct", func(t *testing.T) { 145 type T struct { 146 AA int `json:"aa"` 147 BB string `json:"bb"` 148 CC bool `json:"cc"` 149 } 150 var v struct { 151 A int `json:"abcd"` 152 B string `json:"str"` 153 C bool 154 D *T 155 E func() 156 } 157 content := []byte(` 158 { 159 "abcd": 123, 160 "str" : "hello", 161 "c" : true, 162 "d" : { 163 "aa": 2, 164 "bb": "world", 165 "cc": true 166 }, 167 "e" : null 168 }`) 169 assertErr(t, json.Unmarshal(content, &v)) 170 assertEq(t, "struct.A", 123, v.A) 171 assertEq(t, "struct.B", "hello", v.B) 172 assertEq(t, "struct.C", true, v.C) 173 assertEq(t, "struct.D.AA", 2, v.D.AA) 174 assertEq(t, "struct.D.BB", "world", v.D.BB) 175 assertEq(t, "struct.D.CC", true, v.D.CC) 176 assertEq(t, "struct.E", true, v.E == nil) 177 t.Run("struct.field null", func(t *testing.T) { 178 var v struct { 179 A string 180 B []string 181 C []int 182 D map[string]interface{} 183 E [2]string 184 F interface{} 185 G func() 186 } 187 assertErr(t, json.Unmarshal([]byte(`{"a":null,"b":null,"c":null,"d":null,"e":null,"f":null,"g":null}`), &v)) 188 assertEq(t, "string", v.A, "") 189 assertNeq(t, "[]string", v.B, nil) 190 assertEq(t, "[]string", len(v.B), 0) 191 assertNeq(t, "[]int", v.C, nil) 192 assertEq(t, "[]int", len(v.C), 0) 193 assertNeq(t, "map", v.D, nil) 194 assertEq(t, "map", len(v.D), 0) 195 assertNeq(t, "array", v.E, nil) 196 assertEq(t, "array", len(v.E), 2) 197 assertEq(t, "interface{}", v.F, nil) 198 assertEq(t, "nilfunc", true, v.G == nil) 199 }) 200 }) 201 t.Run("interface", func(t *testing.T) { 202 t.Run("number", func(t *testing.T) { 203 var v interface{} 204 assertErr(t, json.Unmarshal([]byte(`10`), &v)) 205 assertEq(t, "interface.kind", "float64", reflect.TypeOf(v).Kind().String()) 206 assertEq(t, "interface", `10`, fmt.Sprint(v)) 207 }) 208 t.Run("string", func(t *testing.T) { 209 var v interface{} 210 assertErr(t, json.Unmarshal([]byte(`"hello"`), &v)) 211 assertEq(t, "interface.kind", "string", reflect.TypeOf(v).Kind().String()) 212 assertEq(t, "interface", `hello`, fmt.Sprint(v)) 213 }) 214 t.Run("escaped string", func(t *testing.T) { 215 var v interface{} 216 assertErr(t, json.Unmarshal([]byte(`"he\"llo"`), &v)) 217 assertEq(t, "interface.kind", "string", reflect.TypeOf(v).Kind().String()) 218 assertEq(t, "interface", `he"llo`, fmt.Sprint(v)) 219 }) 220 t.Run("bool", func(t *testing.T) { 221 var v interface{} 222 assertErr(t, json.Unmarshal([]byte(`true`), &v)) 223 assertEq(t, "interface.kind", "bool", reflect.TypeOf(v).Kind().String()) 224 assertEq(t, "interface", `true`, fmt.Sprint(v)) 225 }) 226 t.Run("slice", func(t *testing.T) { 227 var v interface{} 228 assertErr(t, json.Unmarshal([]byte(`[1,2,3,4]`), &v)) 229 assertEq(t, "interface.kind", "slice", reflect.TypeOf(v).Kind().String()) 230 assertEq(t, "interface", `[1 2 3 4]`, fmt.Sprint(v)) 231 }) 232 t.Run("map", func(t *testing.T) { 233 var v interface{} 234 assertErr(t, json.Unmarshal([]byte(`{"a": 1, "b": "c"}`), &v)) 235 assertEq(t, "interface.kind", "map", reflect.TypeOf(v).Kind().String()) 236 m := v.(map[string]interface{}) 237 assertEq(t, "interface", `1`, fmt.Sprint(m["a"])) 238 assertEq(t, "interface", `c`, fmt.Sprint(m["b"])) 239 }) 240 t.Run("null", func(t *testing.T) { 241 var v interface{} 242 v = 1 243 assertErr(t, json.Unmarshal([]byte(`null`), &v)) 244 assertEq(t, "interface", nil, v) 245 }) 246 }) 247 t.Run("func", func(t *testing.T) { 248 var v func() 249 assertErr(t, json.Unmarshal([]byte(`null`), &v)) 250 assertEq(t, "nilfunc", true, v == nil) 251 }) 252 } 253 254 func TestIssue98(t *testing.T) { 255 data := "[\"\\" 256 var v interface{} 257 if err := json.Unmarshal([]byte(data), &v); err == nil { 258 t.Fatal("expected error") 259 } 260 } 261 262 func Test_Decoder_UseNumber(t *testing.T) { 263 dec := json.NewDecoder(strings.NewReader(`{"a": 3.14}`)) 264 dec.UseNumber() 265 var v map[string]interface{} 266 assertErr(t, dec.Decode(&v)) 267 assertEq(t, "json.Number", "json.Number", fmt.Sprintf("%T", v["a"])) 268 } 269 270 func Test_Decoder_DisallowUnknownFields(t *testing.T) { 271 dec := json.NewDecoder(strings.NewReader(`{"x": 1}`)) 272 dec.DisallowUnknownFields() 273 var v struct { 274 x int 275 } 276 err := dec.Decode(&v) 277 if err == nil { 278 t.Fatal("expected unknown field error") 279 } 280 if err.Error() != `json: unknown field "x"` { 281 t.Fatal("expected unknown field error") 282 } 283 } 284 285 type unmarshalJSON struct { 286 v int 287 } 288 289 func (u *unmarshalJSON) UnmarshalJSON(b []byte) error { 290 var v int 291 if err := json.Unmarshal(b, &v); err != nil { 292 return err 293 } 294 u.v = v 295 return nil 296 } 297 298 func Test_UnmarshalJSON(t *testing.T) { 299 t.Run("*struct", func(t *testing.T) { 300 var v unmarshalJSON 301 assertErr(t, json.Unmarshal([]byte(`10`), &v)) 302 assertEq(t, "unmarshal", 10, v.v) 303 }) 304 } 305 306 type unmarshalText struct { 307 v int 308 } 309 310 func (u *unmarshalText) UnmarshalText(b []byte) error { 311 var v int 312 if err := json.Unmarshal(b, &v); err != nil { 313 return err 314 } 315 u.v = v 316 return nil 317 } 318 319 func Test_UnmarshalText(t *testing.T) { 320 t.Run("*struct", func(t *testing.T) { 321 var v unmarshalText 322 assertErr(t, json.Unmarshal([]byte(`"11"`), &v)) 323 assertEq(t, "unmarshal", v.v, 11) 324 }) 325 } 326 327 func Test_InvalidUnmarshalError(t *testing.T) { 328 t.Run("nil", func(t *testing.T) { 329 var v *struct{} 330 err := fmt.Sprint(json.Unmarshal([]byte(`{}`), v)) 331 assertEq(t, "invalid unmarshal error", "json: Unmarshal(nil *struct {})", err) 332 }) 333 t.Run("non pointer", func(t *testing.T) { 334 var v int 335 err := fmt.Sprint(json.Unmarshal([]byte(`{}`), v)) 336 assertEq(t, "invalid unmarshal error", "json: Unmarshal(non-pointer int)", err) 337 }) 338 } 339 340 func Test_Token(t *testing.T) { 341 dec := json.NewDecoder(strings.NewReader(`{"a": 1, "b": true, "c": [1, "two", null]}`)) 342 cnt := 0 343 for { 344 if _, err := dec.Token(); err != nil { 345 break 346 } 347 cnt++ 348 } 349 if cnt != 12 { 350 t.Fatal("failed to parse token") 351 } 352 } 353 354 func Test_DecodeStream(t *testing.T) { 355 const stream = ` 356 [ 357 {"Name": "Ed", "Text": "Knock knock."}, 358 {"Name": "Sam", "Text": "Who's there?"}, 359 {"Name": "Ed", "Text": "Go fmt."}, 360 {"Name": "Sam", "Text": "Go fmt who?"}, 361 {"Name": "Ed", "Text": "Go fmt yourself!"} 362 ] 363 ` 364 type Message struct { 365 Name, Text string 366 } 367 dec := json.NewDecoder(strings.NewReader(stream)) 368 369 tk, err := dec.Token() 370 assertErr(t, err) 371 assertEq(t, "[", fmt.Sprint(tk), "[") 372 373 elem := 0 374 // while the array contains values 375 for dec.More() { 376 var m Message 377 // decode an array value (Message) 378 assertErr(t, dec.Decode(&m)) 379 if m.Name == "" || m.Text == "" { 380 t.Fatal("failed to assign value to struct field") 381 } 382 elem++ 383 } 384 assertEq(t, "decode count", elem, 5) 385 386 tk, err = dec.Token() 387 assertErr(t, err) 388 assertEq(t, "]", fmt.Sprint(tk), "]") 389 } 390 391 type T struct { 392 X string 393 Y int 394 Z int `json:"-"` 395 } 396 397 type U struct { 398 Alphabet string `json:"alpha"` 399 } 400 401 type V struct { 402 F1 interface{} 403 F2 int32 404 F3 json.Number 405 F4 *VOuter 406 } 407 408 type VOuter struct { 409 V V 410 } 411 412 type W struct { 413 S SS 414 } 415 416 type P struct { 417 PP PP 418 } 419 420 type PP struct { 421 T T 422 Ts []T 423 } 424 425 type SS string 426 427 func (*SS) UnmarshalJSON(data []byte) error { 428 return &json.UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(SS(""))} 429 } 430 431 // ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and 432 // without UseNumber 433 var ifaceNumAsFloat64 = map[string]interface{}{ 434 "k1": float64(1), 435 "k2": "s", 436 "k3": []interface{}{float64(1), float64(2.0), float64(3e-3)}, 437 "k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)}, 438 } 439 440 var ifaceNumAsNumber = map[string]interface{}{ 441 "k1": json.Number("1"), 442 "k2": "s", 443 "k3": []interface{}{json.Number("1"), json.Number("2.0"), json.Number("3e-3")}, 444 "k4": map[string]interface{}{"kk1": "s", "kk2": json.Number("2")}, 445 } 446 447 type tx struct { 448 x int 449 } 450 451 type u8 uint8 452 453 // A type that can unmarshal itself. 454 455 type unmarshaler struct { 456 T bool 457 } 458 459 func (u *unmarshaler) UnmarshalJSON(b []byte) error { 460 *u = unmarshaler{true} // All we need to see that UnmarshalJSON is called. 461 return nil 462 } 463 464 type ustruct struct { 465 M unmarshaler 466 } 467 468 var _ encoding.TextUnmarshaler = (*unmarshalerText)(nil) 469 470 type ustructText struct { 471 M unmarshalerText 472 } 473 474 // u8marshal is an integer type that can marshal/unmarshal itself. 475 type u8marshal uint8 476 477 func (u8 u8marshal) MarshalText() ([]byte, error) { 478 return []byte(fmt.Sprintf("u%d", u8)), nil 479 } 480 481 var errMissingU8Prefix = errors.New("missing 'u' prefix") 482 483 func (u8 *u8marshal) UnmarshalText(b []byte) error { 484 if !bytes.HasPrefix(b, []byte{'u'}) { 485 return errMissingU8Prefix 486 } 487 n, err := strconv.Atoi(string(b[1:])) 488 if err != nil { 489 return err 490 } 491 *u8 = u8marshal(n) 492 return nil 493 } 494 495 var _ encoding.TextUnmarshaler = (*u8marshal)(nil) 496 497 var ( 498 umtrue = unmarshaler{true} 499 umslice = []unmarshaler{{true}} 500 umstruct = ustruct{unmarshaler{true}} 501 502 umtrueXY = unmarshalerText{"x", "y"} 503 umsliceXY = []unmarshalerText{{"x", "y"}} 504 umstructXY = ustructText{unmarshalerText{"x", "y"}} 505 506 ummapXY = map[unmarshalerText]bool{{"x", "y"}: true} 507 ) 508 509 // Test data structures for anonymous fields. 510 511 type Point struct { 512 Z int 513 } 514 515 type Top struct { 516 Level0 int 517 Embed0 518 *Embed0a 519 *Embed0b `json:"e,omitempty"` // treated as named 520 Embed0c `json:"-"` // ignored 521 Loop 522 Embed0p // has Point with X, Y, used 523 Embed0q // has Point with Z, used 524 embed // contains exported field 525 } 526 527 type Embed0 struct { 528 Level1a int // overridden by Embed0a's Level1a with json tag 529 Level1b int // used because Embed0a's Level1b is renamed 530 Level1c int // used because Embed0a's Level1c is ignored 531 Level1d int // annihilated by Embed0a's Level1d 532 Level1e int `json:"x"` // annihilated by Embed0a.Level1e 533 } 534 535 type Embed0a struct { 536 Level1a int `json:"Level1a,omitempty"` 537 Level1b int `json:"LEVEL1B,omitempty"` 538 Level1c int `json:"-"` 539 Level1d int // annihilated by Embed0's Level1d 540 Level1f int `json:"x"` // annihilated by Embed0's Level1e 541 } 542 543 type Embed0b Embed0 544 545 type Embed0c Embed0 546 547 type Embed0p struct { 548 image.Point 549 } 550 551 type Embed0q struct { 552 Point 553 } 554 555 type embed struct { 556 Q int 557 } 558 559 type Loop struct { 560 Loop1 int `json:",omitempty"` 561 Loop2 int `json:",omitempty"` 562 *Loop 563 } 564 565 // From reflect test: 566 // The X in S6 and S7 annihilate, but they also block the X in S8.S9. 567 type S5 struct { 568 S6 569 S7 570 S8 571 } 572 573 type S6 struct { 574 X int 575 } 576 577 type S7 S6 578 579 type S8 struct { 580 S9 581 } 582 583 type S9 struct { 584 X int 585 Y int 586 } 587 588 // From reflect test: 589 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9. 590 type S10 struct { 591 S11 592 S12 593 S13 594 } 595 596 type S11 struct { 597 S6 598 } 599 600 type S12 struct { 601 S6 602 } 603 604 type S13 struct { 605 S8 606 } 607 608 type Ambig struct { 609 // Given "hello", the first match should win. 610 First int `json:"HELLO"` 611 Second int `json:"Hello"` 612 } 613 614 type XYZ struct { 615 X interface{} 616 Y interface{} 617 Z interface{} 618 } 619 620 type unexportedWithMethods struct{} 621 622 func (unexportedWithMethods) F() {} 623 624 type byteWithMarshalJSON byte 625 626 func (b byteWithMarshalJSON) MarshalJSON() ([]byte, error) { 627 return []byte(fmt.Sprintf(`"Z%.2x"`, byte(b))), nil 628 } 629 630 func (b *byteWithMarshalJSON) UnmarshalJSON(data []byte) error { 631 if len(data) != 5 || data[0] != '"' || data[1] != 'Z' || data[4] != '"' { 632 return fmt.Errorf("bad quoted string") 633 } 634 i, err := strconv.ParseInt(string(data[2:4]), 16, 8) 635 if err != nil { 636 return fmt.Errorf("bad hex") 637 } 638 *b = byteWithMarshalJSON(i) 639 return nil 640 } 641 642 type byteWithPtrMarshalJSON byte 643 644 func (b *byteWithPtrMarshalJSON) MarshalJSON() ([]byte, error) { 645 return byteWithMarshalJSON(*b).MarshalJSON() 646 } 647 648 func (b *byteWithPtrMarshalJSON) UnmarshalJSON(data []byte) error { 649 return (*byteWithMarshalJSON)(b).UnmarshalJSON(data) 650 } 651 652 type byteWithMarshalText byte 653 654 func (b byteWithMarshalText) MarshalText() ([]byte, error) { 655 return []byte(fmt.Sprintf(`Z%.2x`, byte(b))), nil 656 } 657 658 func (b *byteWithMarshalText) UnmarshalText(data []byte) error { 659 if len(data) != 3 || data[0] != 'Z' { 660 return fmt.Errorf("bad quoted string") 661 } 662 i, err := strconv.ParseInt(string(data[1:3]), 16, 8) 663 if err != nil { 664 return fmt.Errorf("bad hex") 665 } 666 *b = byteWithMarshalText(i) 667 return nil 668 } 669 670 type byteWithPtrMarshalText byte 671 672 func (b *byteWithPtrMarshalText) MarshalText() ([]byte, error) { 673 return byteWithMarshalText(*b).MarshalText() 674 } 675 676 func (b *byteWithPtrMarshalText) UnmarshalText(data []byte) error { 677 return (*byteWithMarshalText)(b).UnmarshalText(data) 678 } 679 680 type intWithMarshalJSON int 681 682 func (b intWithMarshalJSON) MarshalJSON() ([]byte, error) { 683 return []byte(fmt.Sprintf(`"Z%.2x"`, int(b))), nil 684 } 685 686 func (b *intWithMarshalJSON) UnmarshalJSON(data []byte) error { 687 if len(data) != 5 || data[0] != '"' || data[1] != 'Z' || data[4] != '"' { 688 return fmt.Errorf("bad quoted string") 689 } 690 i, err := strconv.ParseInt(string(data[2:4]), 16, 8) 691 if err != nil { 692 return fmt.Errorf("bad hex") 693 } 694 *b = intWithMarshalJSON(i) 695 return nil 696 } 697 698 type intWithPtrMarshalJSON int 699 700 func (b *intWithPtrMarshalJSON) MarshalJSON() ([]byte, error) { 701 return intWithMarshalJSON(*b).MarshalJSON() 702 } 703 704 func (b *intWithPtrMarshalJSON) UnmarshalJSON(data []byte) error { 705 return (*intWithMarshalJSON)(b).UnmarshalJSON(data) 706 } 707 708 type intWithMarshalText int 709 710 func (b intWithMarshalText) MarshalText() ([]byte, error) { 711 return []byte(fmt.Sprintf(`Z%.2x`, int(b))), nil 712 } 713 714 func (b *intWithMarshalText) UnmarshalText(data []byte) error { 715 if len(data) != 3 || data[0] != 'Z' { 716 return fmt.Errorf("bad quoted string") 717 } 718 i, err := strconv.ParseInt(string(data[1:3]), 16, 8) 719 if err != nil { 720 return fmt.Errorf("bad hex") 721 } 722 *b = intWithMarshalText(i) 723 return nil 724 } 725 726 type intWithPtrMarshalText int 727 728 func (b *intWithPtrMarshalText) MarshalText() ([]byte, error) { 729 return intWithMarshalText(*b).MarshalText() 730 } 731 732 func (b *intWithPtrMarshalText) UnmarshalText(data []byte) error { 733 return (*intWithMarshalText)(b).UnmarshalText(data) 734 } 735 736 type mapStringToStringData struct { 737 Data map[string]string `json:"data"` 738 } 739 740 type unmarshalTest struct { 741 in string 742 ptr interface{} // new(type) 743 out interface{} 744 err error 745 useNumber bool 746 golden bool 747 disallowUnknownFields bool 748 } 749 750 type B struct { 751 B bool `json:",string"` 752 } 753 754 type DoublePtr struct { 755 I **int 756 J **int 757 } 758 759 var unmarshalTests = []unmarshalTest{ 760 // basic types 761 {in: `true`, ptr: new(bool), out: true}, // 0 762 {in: `1`, ptr: new(int), out: 1}, // 1 763 {in: `1.2`, ptr: new(float64), out: 1.2}, // 2 764 {in: `-5`, ptr: new(int16), out: int16(-5)}, // 3 765 {in: `2`, ptr: new(json.Number), out: json.Number("2"), useNumber: true}, // 4 766 {in: `2`, ptr: new(json.Number), out: json.Number("2")}, // 5 767 {in: `2`, ptr: new(interface{}), out: float64(2.0)}, // 6 768 {in: `2`, ptr: new(interface{}), out: json.Number("2"), useNumber: true}, // 7 769 {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"}, // 8 770 {in: `"http:\/\/"`, ptr: new(string), out: "http://"}, // 9 771 {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"}, // 10 772 {in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"}, // 11 773 {in: "null", ptr: new(interface{}), out: nil}, // 12 774 {in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &json.UnmarshalTypeError{"array", reflect.TypeOf(""), 7, "T", "X"}}, // 13 775 {in: `{"X": 23}`, ptr: new(T), out: T{}, err: &json.UnmarshalTypeError{"number", reflect.TypeOf(""), 8, "T", "X"}}, {in: `{"x": 1}`, ptr: new(tx), out: tx{}}, // 14 776 {in: `{"x": 1}`, ptr: new(tx), out: tx{}}, // 15, 16 777 {in: `{"x": 1}`, ptr: new(tx), err: fmt.Errorf("json: unknown field \"x\""), disallowUnknownFields: true}, // 17 778 {in: `{"S": 23}`, ptr: new(W), out: W{}, err: &json.UnmarshalTypeError{"number", reflect.TypeOf(SS("")), 0, "W", "S"}}, // 18 779 {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: json.Number("3")}}, // 19 780 {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: json.Number("1"), F2: int32(2), F3: json.Number("3")}, useNumber: true}, // 20 781 {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64}, // 21 782 {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsNumber, useNumber: true}, // 22 783 784 // raw values with whitespace 785 {in: "\n true ", ptr: new(bool), out: true}, // 23 786 {in: "\t 1 ", ptr: new(int), out: 1}, // 24 787 {in: "\r 1.2 ", ptr: new(float64), out: 1.2}, // 25 788 {in: "\t -5 \n", ptr: new(int16), out: int16(-5)}, // 26 789 {in: "\t \"a\\u1234\" \n", ptr: new(string), out: "a\u1234"}, // 27 790 791 // Z has a "-" tag. 792 {in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}}, // 28 793 {in: `{"Y": 1, "Z": 2}`, ptr: new(T), err: fmt.Errorf("json: unknown field \"Z\""), disallowUnknownFields: true}, // 29 794 795 {in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}}, // 30 796 {in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), err: fmt.Errorf("json: unknown field \"alphabet\""), disallowUnknownFields: true}, // 31 797 {in: `{"alpha": "abc"}`, ptr: new(U), out: U{Alphabet: "abc"}}, // 32 798 {in: `{"alphabet": "xyz"}`, ptr: new(U), out: U{}}, // 33 799 {in: `{"alphabet": "xyz"}`, ptr: new(U), err: fmt.Errorf("json: unknown field \"alphabet\""), disallowUnknownFields: true}, // 34 800 801 // syntax errors 802 {in: `{"X": "foo", "Y"}`, err: json.NewSyntaxError("invalid character '}' after object key", 17)}, // 35 803 {in: `[1, 2, 3+]`, err: json.NewSyntaxError("invalid character '+' after array element", 9)}, // 36 804 {in: `{"X":12x}`, err: json.NewSyntaxError("invalid character 'x' after object key:value pair", 8), useNumber: true}, // 37 805 {in: `[2, 3`, err: json.NewSyntaxError("unexpected end of JSON input", 5)}, // 38 806 {in: `{"F3": -}`, ptr: new(V), out: V{F3: json.Number("-")}, err: json.NewSyntaxError("strconv.ParseFloat: parsing \"-\": invalid syntax", 9)}, // 39 807 808 // raw value errors 809 {in: "\x01 42", err: json.NewSyntaxError("invalid character '\\x01' looking for beginning of value", 1)}, // 40 810 {in: " 42 \x01", err: json.NewSyntaxError("invalid character '\\x01' after top-level value", 5)}, // 41 811 {in: "\x01 true", err: json.NewSyntaxError("invalid character '\\x01' looking for beginning of value", 1)}, // 42 812 {in: " false \x01", err: json.NewSyntaxError("invalid character '\\x01' after top-level value", 8)}, // 43 813 {in: "\x01 1.2", err: json.NewSyntaxError("invalid character '\\x01' looking for beginning of value", 1)}, // 44 814 {in: " 3.4 \x01", err: json.NewSyntaxError("invalid character '\\x01' after top-level value", 6)}, // 45 815 {in: "\x01 \"string\"", err: json.NewSyntaxError("invalid character '\\x01' looking for beginning of value", 1)}, // 46 816 {in: " \"string\" \x01", err: json.NewSyntaxError("invalid character '\\x01' after top-level value", 11)}, // 47 817 818 // array tests 819 {in: `[1, 2, 3]`, ptr: new([3]int), out: [3]int{1, 2, 3}}, // 48 820 {in: `[1, 2, 3]`, ptr: new([1]int), out: [1]int{1}}, // 49 821 {in: `[1, 2, 3]`, ptr: new([5]int), out: [5]int{1, 2, 3, 0, 0}}, // 50 822 {in: `[1, 2, 3]`, ptr: new(MustNotUnmarshalJSON), err: errors.New("MustNotUnmarshalJSON was used")}, // 51 823 824 // empty array to interface test 825 {in: `[]`, ptr: new([]interface{}), out: []interface{}{}}, //52 826 {in: `null`, ptr: new([]interface{}), out: []interface{}(nil)}, //53 827 {in: `{"T":[]}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": []interface{}{}}}, //54 828 {in: `{"T":null}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": interface{}(nil)}}, // 55 829 830 // composite tests 831 {in: allValueIndent, ptr: new(All), out: allValue}, // 56 832 {in: allValueCompact, ptr: new(All), out: allValue}, // 57 833 {in: allValueIndent, ptr: new(*All), out: &allValue}, // 58 834 {in: allValueCompact, ptr: new(*All), out: &allValue}, // 59 835 {in: pallValueIndent, ptr: new(All), out: pallValue}, // 60 836 {in: pallValueCompact, ptr: new(All), out: pallValue}, // 61 837 {in: pallValueIndent, ptr: new(*All), out: &pallValue}, // 62 838 {in: pallValueCompact, ptr: new(*All), out: &pallValue}, // 63 839 840 // unmarshal interface test 841 {in: `{"T":false}`, ptr: new(unmarshaler), out: umtrue}, // use "false" so test will fail if custom unmarshaler is not called 842 {in: `{"T":false}`, ptr: new(*unmarshaler), out: &umtrue}, // 65 843 {in: `[{"T":false}]`, ptr: new([]unmarshaler), out: umslice}, // 66 844 {in: `[{"T":false}]`, ptr: new(*[]unmarshaler), out: &umslice}, // 67 845 {in: `{"M":{"T":"x:y"}}`, ptr: new(ustruct), out: umstruct}, // 68 846 847 // UnmarshalText interface test 848 {in: `"x:y"`, ptr: new(unmarshalerText), out: umtrueXY}, // 69 849 {in: `"x:y"`, ptr: new(*unmarshalerText), out: &umtrueXY}, // 70 850 {in: `["x:y"]`, ptr: new([]unmarshalerText), out: umsliceXY}, // 71 851 {in: `["x:y"]`, ptr: new(*[]unmarshalerText), out: &umsliceXY}, // 72 852 {in: `{"M":"x:y"}`, ptr: new(ustructText), out: umstructXY}, // 73 853 // integer-keyed map test 854 { 855 in: `{"-1":"a","0":"b","1":"c"}`, // 74 856 ptr: new(map[int]string), 857 out: map[int]string{-1: "a", 0: "b", 1: "c"}, 858 }, 859 { 860 in: `{"0":"a","10":"c","9":"b"}`, // 75 861 ptr: new(map[u8]string), 862 out: map[u8]string{0: "a", 9: "b", 10: "c"}, 863 }, 864 { 865 in: `{"-9223372036854775808":"min","9223372036854775807":"max"}`, // 76 866 ptr: new(map[int64]string), 867 out: map[int64]string{math.MinInt64: "min", math.MaxInt64: "max"}, 868 }, 869 { 870 in: `{"18446744073709551615":"max"}`, // 77 871 ptr: new(map[uint64]string), 872 out: map[uint64]string{math.MaxUint64: "max"}, 873 }, 874 { 875 in: `{"0":false,"10":true}`, // 78 876 ptr: new(map[uintptr]bool), 877 out: map[uintptr]bool{0: false, 10: true}, 878 }, 879 // Check that MarshalText and UnmarshalText take precedence 880 // over default integer handling in map keys. 881 { 882 in: `{"u2":4}`, // 79 883 ptr: new(map[u8marshal]int), 884 out: map[u8marshal]int{2: 4}, 885 }, 886 { 887 in: `{"2":4}`, // 80 888 ptr: new(map[u8marshal]int), 889 err: errMissingU8Prefix, 890 }, 891 // integer-keyed map errors 892 { 893 in: `{"abc":"abc"}`, // 81 894 ptr: new(map[int]string), 895 err: &json.UnmarshalTypeError{Value: "number a", Type: reflect.TypeOf(0), Offset: 2}, 896 }, 897 { 898 in: `{"256":"abc"}`, // 82 899 ptr: new(map[uint8]string), 900 err: &json.UnmarshalTypeError{Value: "number 256", Type: reflect.TypeOf(uint8(0)), Offset: 2}, 901 }, 902 { 903 in: `{"128":"abc"}`, // 83 904 ptr: new(map[int8]string), 905 err: &json.UnmarshalTypeError{Value: "number 128", Type: reflect.TypeOf(int8(0)), Offset: 2}, 906 }, 907 { 908 in: `{"-1":"abc"}`, // 84 909 ptr: new(map[uint8]string), 910 err: &json.UnmarshalTypeError{Value: "number -", Type: reflect.TypeOf(uint8(0)), Offset: 2}, 911 }, 912 { 913 in: `{"F":{"a":2,"3":4}}`, // 85 914 ptr: new(map[string]map[int]int), 915 err: &json.UnmarshalTypeError{Value: "number a", Type: reflect.TypeOf(int(0)), Offset: 7}, 916 }, 917 { 918 in: `{"F":{"a":2,"3":4}}`, // 86 919 ptr: new(map[string]map[uint]int), 920 err: &json.UnmarshalTypeError{Value: "number a", Type: reflect.TypeOf(uint(0)), Offset: 7}, 921 }, 922 // Map keys can be encoding.TextUnmarshalers. 923 {in: `{"x:y":true}`, ptr: new(map[unmarshalerText]bool), out: ummapXY}, // 87 924 // If multiple values for the same key exists, only the most recent value is used. 925 {in: `{"x:y":false,"x:y":true}`, ptr: new(map[unmarshalerText]bool), out: ummapXY}, // 88 926 { // 89 927 in: `{ 928 "Level0": 1, 929 "Level1b": 2, 930 "Level1c": 3, 931 "x": 4, 932 "Level1a": 5, 933 "LEVEL1B": 6, 934 "e": { 935 "Level1a": 8, 936 "Level1b": 9, 937 "Level1c": 10, 938 "Level1d": 11, 939 "x": 12 940 }, 941 "Loop1": 13, 942 "Loop2": 14, 943 "X": 15, 944 "Y": 16, 945 "Z": 17, 946 "Q": 18 947 }`, 948 ptr: new(Top), 949 out: Top{ 950 Level0: 1, 951 Embed0: Embed0{ 952 Level1b: 2, 953 Level1c: 3, 954 }, 955 Embed0a: &Embed0a{ 956 Level1a: 5, 957 Level1b: 6, 958 }, 959 Embed0b: &Embed0b{ 960 Level1a: 8, 961 Level1b: 9, 962 Level1c: 10, 963 Level1d: 11, 964 Level1e: 12, 965 }, 966 Loop: Loop{ 967 Loop1: 13, 968 Loop2: 14, 969 }, 970 Embed0p: Embed0p{ 971 Point: image.Point{X: 15, Y: 16}, 972 }, 973 Embed0q: Embed0q{ 974 Point: Point{Z: 17}, 975 }, 976 embed: embed{ 977 Q: 18, 978 }, 979 }, 980 }, 981 { 982 in: `{"hello": 1}`, // 90 983 ptr: new(Ambig), 984 out: Ambig{First: 1}, 985 }, 986 { 987 in: `{"X": 1,"Y":2}`, // 91 988 ptr: new(S5), 989 out: S5{S8: S8{S9: S9{Y: 2}}}, 990 }, 991 { 992 in: `{"X": 1,"Y":2}`, // 92 993 ptr: new(S5), 994 err: fmt.Errorf("json: unknown field \"X\""), 995 disallowUnknownFields: true, 996 }, 997 { 998 in: `{"X": 1,"Y":2}`, // 93 999 ptr: new(S10), 1000 out: S10{S13: S13{S8: S8{S9: S9{Y: 2}}}}, 1001 }, 1002 { 1003 in: `{"X": 1,"Y":2}`, // 94 1004 ptr: new(S10), 1005 err: fmt.Errorf("json: unknown field \"X\""), 1006 disallowUnknownFields: true, 1007 }, 1008 { 1009 in: `{"I": 0, "I": null, "J": null}`, // 95 1010 ptr: new(DoublePtr), 1011 out: DoublePtr{I: nil, J: nil}, 1012 }, 1013 { 1014 in: "\"hello\\ud800world\"", // 96 1015 ptr: new(string), 1016 out: "hello\ufffdworld", 1017 }, 1018 { 1019 in: "\"hello\\ud800\\ud800world\"", // 97 1020 ptr: new(string), 1021 out: "hello\ufffd\ufffdworld", 1022 }, 1023 { 1024 in: "\"hello\\ud800\\ud800world\"", // 98 1025 ptr: new(string), 1026 out: "hello\ufffd\ufffdworld", 1027 }, 1028 // Used to be issue 8305, but time.Time implements encoding.TextUnmarshaler so this works now. 1029 { 1030 in: `{"2009-11-10T23:00:00Z": "hello world"}`, // 99 1031 ptr: new(map[time.Time]string), 1032 out: map[time.Time]string{time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC): "hello world"}, 1033 }, 1034 // issue 8305 1035 { 1036 in: `{"2009-11-10T23:00:00Z": "hello world"}`, // 100 1037 ptr: new(map[Point]string), 1038 err: &json.UnmarshalTypeError{Value: "object", Type: reflect.TypeOf(Point{}), Offset: 0}, 1039 }, 1040 { 1041 in: `{"asdf": "hello world"}`, // 101 1042 ptr: new(map[unmarshaler]string), 1043 err: &json.UnmarshalTypeError{Value: "object", Type: reflect.TypeOf(unmarshaler{}), Offset: 1}, 1044 }, 1045 // related to issue 13783. 1046 // Go 1.7 changed marshaling a slice of typed byte to use the methods on the byte type, 1047 // similar to marshaling a slice of typed int. 1048 // These tests check that, assuming the byte type also has valid decoding methods, 1049 // either the old base64 string encoding or the new per-element encoding can be 1050 // successfully unmarshaled. The custom unmarshalers were accessible in earlier 1051 // versions of Go, even though the custom marshaler was not. 1052 { 1053 in: `"AQID"`, // 102 1054 ptr: new([]byteWithMarshalJSON), 1055 out: []byteWithMarshalJSON{1, 2, 3}, 1056 }, 1057 { 1058 in: `["Z01","Z02","Z03"]`, // 103 1059 ptr: new([]byteWithMarshalJSON), 1060 out: []byteWithMarshalJSON{1, 2, 3}, 1061 golden: true, 1062 }, 1063 { 1064 in: `"AQID"`, // 104 1065 ptr: new([]byteWithMarshalText), 1066 out: []byteWithMarshalText{1, 2, 3}, 1067 }, 1068 { 1069 in: `["Z01","Z02","Z03"]`, // 105 1070 ptr: new([]byteWithMarshalText), 1071 out: []byteWithMarshalText{1, 2, 3}, 1072 golden: true, 1073 }, 1074 { 1075 in: `"AQID"`, // 106 1076 ptr: new([]byteWithPtrMarshalJSON), 1077 out: []byteWithPtrMarshalJSON{1, 2, 3}, 1078 }, 1079 { 1080 in: `["Z01","Z02","Z03"]`, // 107 1081 ptr: new([]byteWithPtrMarshalJSON), 1082 out: []byteWithPtrMarshalJSON{1, 2, 3}, 1083 golden: true, 1084 }, 1085 { 1086 in: `"AQID"`, // 108 1087 ptr: new([]byteWithPtrMarshalText), 1088 out: []byteWithPtrMarshalText{1, 2, 3}, 1089 }, 1090 { 1091 in: `["Z01","Z02","Z03"]`, // 109 1092 ptr: new([]byteWithPtrMarshalText), 1093 out: []byteWithPtrMarshalText{1, 2, 3}, 1094 golden: true, 1095 }, 1096 1097 // ints work with the marshaler but not the base64 []byte case 1098 { 1099 in: `["Z01","Z02","Z03"]`, // 110 1100 ptr: new([]intWithMarshalJSON), 1101 out: []intWithMarshalJSON{1, 2, 3}, 1102 golden: true, 1103 }, 1104 { 1105 in: `["Z01","Z02","Z03"]`, // 111 1106 ptr: new([]intWithMarshalText), 1107 out: []intWithMarshalText{1, 2, 3}, 1108 golden: true, 1109 }, 1110 { 1111 in: `["Z01","Z02","Z03"]`, // 112 1112 ptr: new([]intWithPtrMarshalJSON), 1113 out: []intWithPtrMarshalJSON{1, 2, 3}, 1114 golden: true, 1115 }, 1116 { 1117 in: `["Z01","Z02","Z03"]`, // 113 1118 ptr: new([]intWithPtrMarshalText), 1119 out: []intWithPtrMarshalText{1, 2, 3}, 1120 golden: true, 1121 }, 1122 1123 {in: `0.000001`, ptr: new(float64), out: 0.000001, golden: true}, // 114 1124 {in: `1e-07`, ptr: new(float64), out: 1e-7, golden: true}, // 115 1125 {in: `100000000000000000000`, ptr: new(float64), out: 100000000000000000000.0, golden: true}, // 116 1126 {in: `1e+21`, ptr: new(float64), out: 1e21, golden: true}, // 117 1127 {in: `-0.000001`, ptr: new(float64), out: -0.000001, golden: true}, // 118 1128 {in: `-1e-07`, ptr: new(float64), out: -1e-7, golden: true}, // 119 1129 {in: `-100000000000000000000`, ptr: new(float64), out: -100000000000000000000.0, golden: true}, // 120 1130 {in: `-1e+21`, ptr: new(float64), out: -1e21, golden: true}, // 121 1131 {in: `999999999999999900000`, ptr: new(float64), out: 999999999999999900000.0, golden: true}, // 122 1132 {in: `9007199254740992`, ptr: new(float64), out: 9007199254740992.0, golden: true}, // 123 1133 {in: `9007199254740993`, ptr: new(float64), out: 9007199254740992.0, golden: false}, // 124 1134 { 1135 in: `{"V": {"F2": "hello"}}`, // 125 1136 ptr: new(VOuter), 1137 err: &json.UnmarshalTypeError{ 1138 Value: `number hello`, 1139 Struct: "V", 1140 Field: "F2", 1141 Type: reflect.TypeOf(int32(0)), 1142 Offset: 20, 1143 }, 1144 }, 1145 { 1146 in: `{"V": {"F4": {}, "F2": "hello"}}`, // 126 1147 ptr: new(VOuter), 1148 err: &json.UnmarshalTypeError{ 1149 Value: `number hello`, 1150 Struct: "V", 1151 Field: "F2", 1152 Type: reflect.TypeOf(int32(0)), 1153 Offset: 30, 1154 }, 1155 }, 1156 // issue 15146. 1157 // invalid inputs in wrongStringTests below. 1158 {in: `{"B":"true"}`, ptr: new(B), out: B{true}, golden: true}, // 127 1159 {in: `{"B":"false"}`, ptr: new(B), out: B{false}, golden: true}, // 128 1160 {in: `{"B": "maybe"}`, ptr: new(B), err: errors.New(`json: bool unexpected end of JSON input`)}, // 129 1161 {in: `{"B": "tru"}`, ptr: new(B), err: errors.New(`json: invalid character as true`)}, // 130 1162 {in: `{"B": "False"}`, ptr: new(B), err: errors.New(`json: bool unexpected end of JSON input`)}, // 131 1163 {in: `{"B": "null"}`, ptr: new(B), out: B{false}}, // 132 1164 {in: `{"B": "nul"}`, ptr: new(B), err: errors.New(`json: invalid character as null`)}, // 133 1165 {in: `{"B": [2, 3]}`, ptr: new(B), err: errors.New(`json: cannot unmarshal array into Go struct field B.B of type string`)}, // 134 1166 // additional tests for disallowUnknownFields 1167 { // 135 1168 in: `{ 1169 "Level0": 1, 1170 "Level1b": 2, 1171 "Level1c": 3, 1172 "x": 4, 1173 "Level1a": 5, 1174 "LEVEL1B": 6, 1175 "e": { 1176 "Level1a": 8, 1177 "Level1b": 9, 1178 "Level1c": 10, 1179 "Level1d": 11, 1180 "x": 12 1181 }, 1182 "Loop1": 13, 1183 "Loop2": 14, 1184 "X": 15, 1185 "Y": 16, 1186 "Z": 17, 1187 "Q": 18, 1188 "extra": true 1189 }`, 1190 ptr: new(Top), 1191 err: fmt.Errorf("json: unknown field \"extra\""), 1192 disallowUnknownFields: true, 1193 }, 1194 { // 136 1195 in: `{ 1196 "Level0": 1, 1197 "Level1b": 2, 1198 "Level1c": 3, 1199 "x": 4, 1200 "Level1a": 5, 1201 "LEVEL1B": 6, 1202 "e": { 1203 "Level1a": 8, 1204 "Level1b": 9, 1205 "Level1c": 10, 1206 "Level1d": 11, 1207 "x": 12, 1208 "extra": null 1209 }, 1210 "Loop1": 13, 1211 "Loop2": 14, 1212 "X": 15, 1213 "Y": 16, 1214 "Z": 17, 1215 "Q": 18 1216 }`, 1217 ptr: new(Top), 1218 err: fmt.Errorf("json: unknown field \"extra\""), 1219 disallowUnknownFields: true, 1220 }, 1221 // issue 26444 1222 // UnmarshalTypeError without field & struct values 1223 { 1224 in: `{"data":{"test1": "bob", "test2": 123}}`, // 137 1225 ptr: new(mapStringToStringData), 1226 err: &json.UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(""), Offset: 37, Struct: "mapStringToStringData", Field: "Data"}, 1227 }, 1228 { 1229 in: `{"data":{"test1": 123, "test2": "bob"}}`, // 138 1230 ptr: new(mapStringToStringData), 1231 err: &json.UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(""), Offset: 21, Struct: "mapStringToStringData", Field: "Data"}, 1232 }, 1233 1234 // trying to decode JSON arrays or objects via TextUnmarshaler 1235 { 1236 in: `[1, 2, 3]`, // 139 1237 ptr: new(MustNotUnmarshalText), 1238 err: &json.UnmarshalTypeError{Value: "array", Type: reflect.TypeOf(&MustNotUnmarshalText{}), Offset: 1}, 1239 }, 1240 { 1241 in: `{"foo": "bar"}`, // 140 1242 ptr: new(MustNotUnmarshalText), 1243 err: &json.UnmarshalTypeError{Value: "object", Type: reflect.TypeOf(&MustNotUnmarshalText{}), Offset: 1}, 1244 }, 1245 // #22369 1246 { 1247 in: `{"PP": {"T": {"Y": "bad-type"}}}`, // 141 1248 ptr: new(P), 1249 err: &json.UnmarshalTypeError{ 1250 Value: `number bad-type`, 1251 Struct: "T", 1252 Field: "Y", 1253 Type: reflect.TypeOf(int(0)), 1254 Offset: 29, 1255 }, 1256 }, 1257 { 1258 in: `{"Ts": [{"Y": 1}, {"Y": 2}, {"Y": "bad-type"}]}`, // 142 1259 ptr: new(PP), 1260 err: &json.UnmarshalTypeError{ 1261 Value: `number bad-type`, 1262 Struct: "T", 1263 Field: "Y", 1264 Type: reflect.TypeOf(int(0)), 1265 Offset: 29, 1266 }, 1267 }, 1268 // #14702 1269 { 1270 in: `invalid`, // 143 1271 ptr: new(json.Number), 1272 err: json.NewSyntaxError( 1273 `invalid character 'i' looking for beginning of value`, 1274 1, 1275 ), 1276 }, 1277 { 1278 in: `"invalid"`, // 144 1279 ptr: new(json.Number), 1280 err: fmt.Errorf(`strconv.ParseFloat: parsing "invalid": invalid syntax`), 1281 }, 1282 { 1283 in: `{"A":"invalid"}`, // 145 1284 ptr: new(struct{ A json.Number }), 1285 err: fmt.Errorf(`strconv.ParseFloat: parsing "invalid": invalid syntax`), 1286 }, 1287 { 1288 in: `{"A":"invalid"}`, // 146 1289 ptr: new(struct { 1290 A json.Number `json:",string"` 1291 }), 1292 err: fmt.Errorf(`json: json.Number unexpected end of JSON input`), 1293 }, 1294 { 1295 in: `{"A":"invalid"}`, // 147 1296 ptr: new(map[string]json.Number), 1297 err: fmt.Errorf(`strconv.ParseFloat: parsing "invalid": invalid syntax`), 1298 }, 1299 // invalid UTF-8 is coerced to valid UTF-8. 1300 { 1301 in: "\"hello\xffworld\"", // 148 1302 ptr: new(string), 1303 out: "hello\ufffdworld", 1304 }, 1305 { 1306 in: "\"hello\xc2\xc2world\"", // 149 1307 ptr: new(string), 1308 out: "hello\ufffd\ufffdworld", 1309 }, 1310 { 1311 in: "\"hello\xc2\xffworld\"", // 150 1312 ptr: new(string), 1313 out: "hello\ufffd\ufffdworld", 1314 }, 1315 { 1316 in: "\"hello\xed\xa0\x80\xed\xb0\x80world\"", // 151 1317 ptr: new(string), 1318 out: "hello\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdworld", 1319 }, 1320 {in: "-128", ptr: new(int8), out: int8(-128)}, 1321 {in: "127", ptr: new(int8), out: int8(127)}, 1322 {in: "-32768", ptr: new(int16), out: int16(-32768)}, 1323 {in: "32767", ptr: new(int16), out: int16(32767)}, 1324 {in: "-2147483648", ptr: new(int32), out: int32(-2147483648)}, 1325 {in: "2147483647", ptr: new(int32), out: int32(2147483647)}, 1326 } 1327 1328 type All struct { 1329 Bool bool 1330 Int int 1331 Int8 int8 1332 Int16 int16 1333 Int32 int32 1334 Int64 int64 1335 Uint uint 1336 Uint8 uint8 1337 Uint16 uint16 1338 Uint32 uint32 1339 Uint64 uint64 1340 Uintptr uintptr 1341 Float32 float32 1342 Float64 float64 1343 1344 Foo string `json:"bar"` 1345 Foo2 string `json:"bar2,dummyopt"` 1346 1347 IntStr int64 `json:",string"` 1348 UintptrStr uintptr `json:",string"` 1349 1350 PBool *bool 1351 PInt *int 1352 PInt8 *int8 1353 PInt16 *int16 1354 PInt32 *int32 1355 PInt64 *int64 1356 PUint *uint 1357 PUint8 *uint8 1358 PUint16 *uint16 1359 PUint32 *uint32 1360 PUint64 *uint64 1361 PUintptr *uintptr 1362 PFloat32 *float32 1363 PFloat64 *float64 1364 1365 String string 1366 PString *string 1367 1368 Map map[string]Small 1369 MapP map[string]*Small 1370 PMap *map[string]Small 1371 PMapP *map[string]*Small 1372 1373 EmptyMap map[string]Small 1374 NilMap map[string]Small 1375 1376 Slice []Small 1377 SliceP []*Small 1378 PSlice *[]Small 1379 PSliceP *[]*Small 1380 1381 EmptySlice []Small 1382 NilSlice []Small 1383 1384 StringSlice []string 1385 ByteSlice []byte 1386 1387 Small Small 1388 PSmall *Small 1389 PPSmall **Small 1390 1391 Interface interface{} 1392 PInterface *interface{} 1393 1394 unexported int 1395 } 1396 1397 type Small struct { 1398 Tag string 1399 } 1400 1401 var allValue = All{ 1402 Bool: true, 1403 Int: 2, 1404 Int8: 3, 1405 Int16: 4, 1406 Int32: 5, 1407 Int64: 6, 1408 Uint: 7, 1409 Uint8: 8, 1410 Uint16: 9, 1411 Uint32: 10, 1412 Uint64: 11, 1413 Uintptr: 12, 1414 Float32: 14.1, 1415 Float64: 15.1, 1416 Foo: "foo", 1417 Foo2: "foo2", 1418 IntStr: 42, 1419 UintptrStr: 44, 1420 String: "16", 1421 Map: map[string]Small{ 1422 "17": {Tag: "tag17"}, 1423 "18": {Tag: "tag18"}, 1424 }, 1425 MapP: map[string]*Small{ 1426 "19": {Tag: "tag19"}, 1427 "20": nil, 1428 }, 1429 EmptyMap: map[string]Small{}, 1430 Slice: []Small{{Tag: "tag20"}, {Tag: "tag21"}}, 1431 SliceP: []*Small{{Tag: "tag22"}, nil, {Tag: "tag23"}}, 1432 EmptySlice: []Small{}, 1433 StringSlice: []string{"str24", "str25", "str26"}, 1434 ByteSlice: []byte{27, 28, 29}, 1435 Small: Small{Tag: "tag30"}, 1436 PSmall: &Small{Tag: "tag31"}, 1437 Interface: 5.2, 1438 } 1439 1440 var pallValue = All{ 1441 PBool: &allValue.Bool, 1442 PInt: &allValue.Int, 1443 PInt8: &allValue.Int8, 1444 PInt16: &allValue.Int16, 1445 PInt32: &allValue.Int32, 1446 PInt64: &allValue.Int64, 1447 PUint: &allValue.Uint, 1448 PUint8: &allValue.Uint8, 1449 PUint16: &allValue.Uint16, 1450 PUint32: &allValue.Uint32, 1451 PUint64: &allValue.Uint64, 1452 PUintptr: &allValue.Uintptr, 1453 PFloat32: &allValue.Float32, 1454 PFloat64: &allValue.Float64, 1455 PString: &allValue.String, 1456 PMap: &allValue.Map, 1457 PMapP: &allValue.MapP, 1458 PSlice: &allValue.Slice, 1459 PSliceP: &allValue.SliceP, 1460 PPSmall: &allValue.PSmall, 1461 PInterface: &allValue.Interface, 1462 } 1463 1464 var allValueIndent = `{ 1465 "Bool": true, 1466 "Int": 2, 1467 "Int8": 3, 1468 "Int16": 4, 1469 "Int32": 5, 1470 "Int64": 6, 1471 "Uint": 7, 1472 "Uint8": 8, 1473 "Uint16": 9, 1474 "Uint32": 10, 1475 "Uint64": 11, 1476 "Uintptr": 12, 1477 "Float32": 14.1, 1478 "Float64": 15.1, 1479 "bar": "foo", 1480 "bar2": "foo2", 1481 "IntStr": "42", 1482 "UintptrStr": "44", 1483 "PBool": null, 1484 "PInt": null, 1485 "PInt8": null, 1486 "PInt16": null, 1487 "PInt32": null, 1488 "PInt64": null, 1489 "PUint": null, 1490 "PUint8": null, 1491 "PUint16": null, 1492 "PUint32": null, 1493 "PUint64": null, 1494 "PUintptr": null, 1495 "PFloat32": null, 1496 "PFloat64": null, 1497 "String": "16", 1498 "PString": null, 1499 "Map": { 1500 "17": { 1501 "Tag": "tag17" 1502 }, 1503 "18": { 1504 "Tag": "tag18" 1505 } 1506 }, 1507 "MapP": { 1508 "19": { 1509 "Tag": "tag19" 1510 }, 1511 "20": null 1512 }, 1513 "PMap": null, 1514 "PMapP": null, 1515 "EmptyMap": {}, 1516 "NilMap": null, 1517 "Slice": [ 1518 { 1519 "Tag": "tag20" 1520 }, 1521 { 1522 "Tag": "tag21" 1523 } 1524 ], 1525 "SliceP": [ 1526 { 1527 "Tag": "tag22" 1528 }, 1529 null, 1530 { 1531 "Tag": "tag23" 1532 } 1533 ], 1534 "PSlice": null, 1535 "PSliceP": null, 1536 "EmptySlice": [], 1537 "NilSlice": null, 1538 "StringSlice": [ 1539 "str24", 1540 "str25", 1541 "str26" 1542 ], 1543 "ByteSlice": "Gxwd", 1544 "Small": { 1545 "Tag": "tag30" 1546 }, 1547 "PSmall": { 1548 "Tag": "tag31" 1549 }, 1550 "PPSmall": null, 1551 "Interface": 5.2, 1552 "PInterface": null 1553 }` 1554 1555 var allValueCompact = strings.Map(noSpace, allValueIndent) 1556 1557 var pallValueIndent = `{ 1558 "Bool": false, 1559 "Int": 0, 1560 "Int8": 0, 1561 "Int16": 0, 1562 "Int32": 0, 1563 "Int64": 0, 1564 "Uint": 0, 1565 "Uint8": 0, 1566 "Uint16": 0, 1567 "Uint32": 0, 1568 "Uint64": 0, 1569 "Uintptr": 0, 1570 "Float32": 0, 1571 "Float64": 0, 1572 "bar": "", 1573 "bar2": "", 1574 "IntStr": "0", 1575 "UintptrStr": "0", 1576 "PBool": true, 1577 "PInt": 2, 1578 "PInt8": 3, 1579 "PInt16": 4, 1580 "PInt32": 5, 1581 "PInt64": 6, 1582 "PUint": 7, 1583 "PUint8": 8, 1584 "PUint16": 9, 1585 "PUint32": 10, 1586 "PUint64": 11, 1587 "PUintptr": 12, 1588 "PFloat32": 14.1, 1589 "PFloat64": 15.1, 1590 "String": "", 1591 "PString": "16", 1592 "Map": null, 1593 "MapP": null, 1594 "PMap": { 1595 "17": { 1596 "Tag": "tag17" 1597 }, 1598 "18": { 1599 "Tag": "tag18" 1600 } 1601 }, 1602 "PMapP": { 1603 "19": { 1604 "Tag": "tag19" 1605 }, 1606 "20": null 1607 }, 1608 "EmptyMap": null, 1609 "NilMap": null, 1610 "Slice": null, 1611 "SliceP": null, 1612 "PSlice": [ 1613 { 1614 "Tag": "tag20" 1615 }, 1616 { 1617 "Tag": "tag21" 1618 } 1619 ], 1620 "PSliceP": [ 1621 { 1622 "Tag": "tag22" 1623 }, 1624 null, 1625 { 1626 "Tag": "tag23" 1627 } 1628 ], 1629 "EmptySlice": null, 1630 "NilSlice": null, 1631 "StringSlice": null, 1632 "ByteSlice": null, 1633 "Small": { 1634 "Tag": "" 1635 }, 1636 "PSmall": null, 1637 "PPSmall": { 1638 "Tag": "tag31" 1639 }, 1640 "Interface": null, 1641 "PInterface": 5.2 1642 }` 1643 1644 var pallValueCompact = strings.Map(noSpace, pallValueIndent) 1645 1646 type NullTest struct { 1647 Bool bool 1648 Int int 1649 Int8 int8 1650 Int16 int16 1651 Int32 int32 1652 Int64 int64 1653 Uint uint 1654 Uint8 uint8 1655 Uint16 uint16 1656 Uint32 uint32 1657 Uint64 uint64 1658 Float32 float32 1659 Float64 float64 1660 String string 1661 PBool *bool 1662 Map map[string]string 1663 Slice []string 1664 Interface interface{} 1665 1666 PRaw *json.RawMessage 1667 PTime *time.Time 1668 PBigInt *big.Int 1669 PText *MustNotUnmarshalText 1670 PBuffer *bytes.Buffer // has methods, just not relevant ones 1671 PStruct *struct{} 1672 1673 Raw json.RawMessage 1674 Time time.Time 1675 BigInt big.Int 1676 Text MustNotUnmarshalText 1677 Buffer bytes.Buffer 1678 Struct struct{} 1679 } 1680 1681 type MustNotUnmarshalJSON struct{} 1682 1683 func (x MustNotUnmarshalJSON) UnmarshalJSON(data []byte) error { 1684 return errors.New("MustNotUnmarshalJSON was used") 1685 } 1686 1687 type MustNotUnmarshalText struct{} 1688 1689 func (x MustNotUnmarshalText) UnmarshalText(text []byte) error { 1690 return errors.New("MustNotUnmarshalText was used") 1691 } 1692 1693 func isSpace(c byte) bool { 1694 return c <= ' ' && (c == ' ' || c == '\t' || c == '\r' || c == '\n') 1695 } 1696 1697 func noSpace(c rune) rune { 1698 if isSpace(byte(c)) { //only used for ascii 1699 return -1 1700 } 1701 return c 1702 } 1703 1704 var badUTF8 = []struct { 1705 in, out string 1706 }{ 1707 {"hello\xffworld", `"hello\ufffdworld"`}, 1708 {"", `""`}, 1709 {"\xff", `"\ufffd"`}, 1710 {"\xff\xff", `"\ufffd\ufffd"`}, 1711 {"a\xffb", `"a\ufffdb"`}, 1712 {"\xe6\x97\xa5\xe6\x9c\xac\xff\xaa\x9e", `"日本\ufffd\ufffd\ufffd"`}, 1713 } 1714 1715 func TestMarshalAllValue(t *testing.T) { 1716 b, err := json.Marshal(allValue) 1717 if err != nil { 1718 t.Fatalf("Marshal allValue: %v", err) 1719 } 1720 if string(b) != allValueCompact { 1721 t.Errorf("Marshal allValueCompact") 1722 diff(t, b, []byte(allValueCompact)) 1723 return 1724 } 1725 1726 b, err = json.Marshal(pallValue) 1727 if err != nil { 1728 t.Fatalf("Marshal pallValue: %v", err) 1729 } 1730 if string(b) != pallValueCompact { 1731 t.Errorf("Marshal pallValueCompact") 1732 diff(t, b, []byte(pallValueCompact)) 1733 return 1734 } 1735 } 1736 1737 func TestMarshalBadUTF8(t *testing.T) { 1738 for _, tt := range badUTF8 { 1739 b, err := json.Marshal(tt.in) 1740 if string(b) != tt.out || err != nil { 1741 t.Errorf("Marshal(%q) = %#q, %v, want %#q, nil", tt.in, b, err, tt.out) 1742 } 1743 } 1744 } 1745 1746 func TestMarshalNumberZeroVal(t *testing.T) { 1747 var n json.Number 1748 out, err := json.Marshal(n) 1749 if err != nil { 1750 t.Fatal(err) 1751 } 1752 outStr := string(out) 1753 if outStr != "0" { 1754 t.Fatalf("Invalid zero val for Number: %q", outStr) 1755 } 1756 } 1757 1758 func TestMarshalEmbeds(t *testing.T) { 1759 top := &Top{ 1760 Level0: 1, 1761 Embed0: Embed0{ 1762 Level1b: 2, 1763 Level1c: 3, 1764 }, 1765 Embed0a: &Embed0a{ 1766 Level1a: 5, 1767 Level1b: 6, 1768 }, 1769 Embed0b: &Embed0b{ 1770 Level1a: 8, 1771 Level1b: 9, 1772 Level1c: 10, 1773 Level1d: 11, 1774 Level1e: 12, 1775 }, 1776 Loop: Loop{ 1777 Loop1: 13, 1778 Loop2: 14, 1779 }, 1780 Embed0p: Embed0p{ 1781 Point: image.Point{X: 15, Y: 16}, 1782 }, 1783 Embed0q: Embed0q{ 1784 Point: Point{Z: 17}, 1785 }, 1786 embed: embed{ 1787 Q: 18, 1788 }, 1789 } 1790 b, err := json.Marshal(top) 1791 if err != nil { 1792 t.Fatal(err) 1793 } 1794 want := "{\"Level0\":1,\"Level1b\":2,\"Level1c\":3,\"Level1a\":5,\"LEVEL1B\":6,\"e\":{\"Level1a\":8,\"Level1b\":9,\"Level1c\":10,\"Level1d\":11,\"x\":12},\"Loop1\":13,\"Loop2\":14,\"X\":15,\"Y\":16,\"Z\":17,\"Q\":18}" 1795 if string(b) != want { 1796 t.Errorf("Wrong marshal result.\n got: %q\nwant: %q", b, want) 1797 } 1798 } 1799 1800 func equalError(a, b error) bool { 1801 if a == nil { 1802 return b == nil 1803 } 1804 if b == nil { 1805 return a == nil 1806 } 1807 return a.Error() == b.Error() 1808 } 1809 1810 func TestUnmarshal(t *testing.T) { 1811 for i, tt := range unmarshalTests { 1812 t.Run(fmt.Sprintf("%d_%q", i, tt.in), func(t *testing.T) { 1813 in := []byte(tt.in) 1814 if tt.ptr == nil { 1815 return 1816 } 1817 1818 typ := reflect.TypeOf(tt.ptr) 1819 if typ.Kind() != reflect.Ptr { 1820 t.Errorf("#%d: unmarshalTest.ptr %T is not a pointer type", i, tt.ptr) 1821 return 1822 } 1823 typ = typ.Elem() 1824 1825 // v = new(right-type) 1826 v := reflect.New(typ) 1827 1828 if !reflect.DeepEqual(tt.ptr, v.Interface()) { 1829 // There's no reason for ptr to point to non-zero data, 1830 // as we decode into new(right-type), so the data is 1831 // discarded. 1832 // This can easily mean tests that silently don't test 1833 // what they should. To test decoding into existing 1834 // data, see TestPrefilled. 1835 t.Errorf("#%d: unmarshalTest.ptr %#v is not a pointer to a zero value", i, tt.ptr) 1836 return 1837 } 1838 1839 dec := json.NewDecoder(bytes.NewReader(in)) 1840 if tt.useNumber { 1841 dec.UseNumber() 1842 } 1843 if tt.disallowUnknownFields { 1844 dec.DisallowUnknownFields() 1845 } 1846 if err := dec.Decode(v.Interface()); !equalError(err, tt.err) { 1847 t.Errorf("#%d: %v, want %v", i, err, tt.err) 1848 return 1849 } else if err != nil { 1850 return 1851 } 1852 if !reflect.DeepEqual(v.Elem().Interface(), tt.out) { 1853 t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out) 1854 data, _ := json.Marshal(v.Elem().Interface()) 1855 println(string(data)) 1856 data, _ = json.Marshal(tt.out) 1857 println(string(data)) 1858 return 1859 } 1860 1861 // Check round trip also decodes correctly. 1862 if tt.err == nil { 1863 enc, err := json.Marshal(v.Interface()) 1864 if err != nil { 1865 t.Errorf("#%d: error re-marshaling: %v", i, err) 1866 return 1867 } 1868 if tt.golden && !bytes.Equal(enc, in) { 1869 t.Errorf("#%d: remarshal mismatch:\nhave: %s\nwant: %s", i, enc, in) 1870 } 1871 vv := reflect.New(reflect.TypeOf(tt.ptr).Elem()) 1872 dec = json.NewDecoder(bytes.NewReader(enc)) 1873 if tt.useNumber { 1874 dec.UseNumber() 1875 } 1876 if err := dec.Decode(vv.Interface()); err != nil { 1877 t.Errorf("#%d: error re-unmarshaling %#q: %v", i, enc, err) 1878 return 1879 } 1880 if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) { 1881 t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface()) 1882 t.Errorf(" In: %q", strings.Map(noSpace, string(in))) 1883 t.Errorf("Marshal: %q", strings.Map(noSpace, string(enc))) 1884 return 1885 } 1886 } 1887 }) 1888 } 1889 } 1890 1891 func TestUnmarshalMarshal(t *testing.T) { 1892 initBig() 1893 var v interface{} 1894 if err := json.Unmarshal(jsonBig, &v); err != nil { 1895 t.Fatalf("Unmarshal: %v", err) 1896 } 1897 b, err := json.Marshal(v) 1898 if err != nil { 1899 t.Fatalf("Marshal: %v", err) 1900 } 1901 if !bytes.Equal(jsonBig, b) { 1902 t.Errorf("Marshal jsonBig") 1903 diff(t, b, jsonBig) 1904 return 1905 } 1906 } 1907 1908 var numberTests = []struct { 1909 in string 1910 i int64 1911 intErr string 1912 f float64 1913 floatErr string 1914 }{ 1915 {in: "-1.23e1", intErr: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f: -1.23e1}, 1916 {in: "-12", i: -12, f: -12.0}, 1917 {in: "1e1000", intErr: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr: "strconv.ParseFloat: parsing \"1e1000\": value out of range"}, 1918 } 1919 1920 // Independent of Decode, basic coverage of the accessors in Number 1921 func TestNumberAccessors(t *testing.T) { 1922 for _, tt := range numberTests { 1923 n := json.Number(tt.in) 1924 if s := n.String(); s != tt.in { 1925 t.Errorf("Number(%q).String() is %q", tt.in, s) 1926 } 1927 if i, err := n.Int64(); err == nil && tt.intErr == "" && i != tt.i { 1928 t.Errorf("Number(%q).Int64() is %d", tt.in, i) 1929 } else if (err == nil && tt.intErr != "") || (err != nil && err.Error() != tt.intErr) { 1930 t.Errorf("Number(%q).Int64() wanted error %q but got: %v", tt.in, tt.intErr, err) 1931 } 1932 if f, err := n.Float64(); err == nil && tt.floatErr == "" && f != tt.f { 1933 t.Errorf("Number(%q).Float64() is %g", tt.in, f) 1934 } else if (err == nil && tt.floatErr != "") || (err != nil && err.Error() != tt.floatErr) { 1935 t.Errorf("Number(%q).Float64() wanted error %q but got: %v", tt.in, tt.floatErr, err) 1936 } 1937 } 1938 } 1939 1940 func TestLargeByteSlice(t *testing.T) { 1941 s0 := make([]byte, 2000) 1942 for i := range s0 { 1943 s0[i] = byte(i) 1944 } 1945 b, err := json.Marshal(s0) 1946 if err != nil { 1947 t.Fatalf("Marshal: %v", err) 1948 } 1949 var s1 []byte 1950 if err := json.Unmarshal(b, &s1); err != nil { 1951 t.Fatalf("Unmarshal: %v", err) 1952 } 1953 if !bytes.Equal(s0, s1) { 1954 t.Errorf("Marshal large byte slice") 1955 diff(t, s0, s1) 1956 } 1957 } 1958 1959 type Xint struct { 1960 X int 1961 } 1962 1963 func TestUnmarshalInterface(t *testing.T) { 1964 var xint Xint 1965 var i interface{} = &xint 1966 if err := json.Unmarshal([]byte(`{"X":1}`), &i); err != nil { 1967 t.Fatalf("Unmarshal: %v", err) 1968 } 1969 if xint.X != 1 { 1970 t.Fatalf("Did not write to xint") 1971 } 1972 } 1973 1974 func TestUnmarshalPtrPtr(t *testing.T) { 1975 var xint Xint 1976 pxint := &xint 1977 if err := json.Unmarshal([]byte(`{"X":1}`), &pxint); err != nil { 1978 t.Fatalf("Unmarshal: %v", err) 1979 } 1980 if xint.X != 1 { 1981 t.Fatalf("Did not write to xint") 1982 } 1983 } 1984 1985 func TestEscape(t *testing.T) { 1986 const input = `"foobar"<html>` + " [\u2028 \u2029]" 1987 const expected = `"\"foobar\"\u003chtml\u003e [\u2028 \u2029]"` 1988 b, err := json.Marshal(input) 1989 if err != nil { 1990 t.Fatalf("Marshal error: %v", err) 1991 } 1992 if s := string(b); s != expected { 1993 t.Errorf("Encoding of [%s]:\n got [%s]\nwant [%s]", input, s, expected) 1994 } 1995 } 1996 1997 // WrongString is a struct that's misusing the ,string modifier. 1998 type WrongString struct { 1999 Message string `json:"result,string"` 2000 } 2001 2002 type wrongStringTest struct { 2003 in, err string 2004 } 2005 2006 var wrongStringTests = []wrongStringTest{ 2007 {`{"result":"x"}`, `invalid character 'x' looking for beginning of value`}, 2008 {`{"result":"foo"}`, `invalid character 'f' looking for beginning of value`}, 2009 {`{"result":"123"}`, `json: cannot unmarshal number into Go struct field WrongString.Message of type string`}, 2010 {`{"result":123}`, `json: cannot unmarshal number into Go struct field WrongString.Message of type string`}, 2011 {`{"result":"\""}`, `json: string unexpected end of JSON input`}, 2012 {`{"result":"\"foo"}`, `json: string unexpected end of JSON input`}, 2013 } 2014 2015 // If people misuse the ,string modifier, the error message should be 2016 // helpful, telling the user that they're doing it wrong. 2017 func TestErrorMessageFromMisusedString(t *testing.T) { 2018 for n, tt := range wrongStringTests { 2019 r := strings.NewReader(tt.in) 2020 var s WrongString 2021 err := json.NewDecoder(r).Decode(&s) 2022 got := fmt.Sprintf("%v", err) 2023 if got != tt.err { 2024 t.Errorf("%d. got err = %q, want %q", n, got, tt.err) 2025 } 2026 } 2027 } 2028 2029 func TestRefUnmarshal(t *testing.T) { 2030 type S struct { 2031 // Ref is defined in encode_test.go. 2032 R0 Ref 2033 R1 *Ref 2034 R2 RefText 2035 R3 *RefText 2036 } 2037 want := S{ 2038 R0: 12, 2039 R1: new(Ref), 2040 R2: 13, 2041 R3: new(RefText), 2042 } 2043 *want.R1 = 12 2044 *want.R3 = 13 2045 2046 var got S 2047 if err := json.Unmarshal([]byte(`{"R0":"ref","R1":"ref","R2":"ref","R3":"ref"}`), &got); err != nil { 2048 t.Fatalf("Unmarshal: %v", err) 2049 } 2050 if !reflect.DeepEqual(got, want) { 2051 t.Errorf("got %+v, want %+v", got, want) 2052 } 2053 } 2054 2055 // Test that the empty string doesn't panic decoding when ,string is specified 2056 // Issue 3450 2057 func TestEmptyString(t *testing.T) { 2058 type T2 struct { 2059 Number1 int `json:",string"` 2060 Number2 int `json:",string"` 2061 } 2062 data := `{"Number1":"1", "Number2":""}` 2063 dec := json.NewDecoder(strings.NewReader(data)) 2064 var t2 T2 2065 err := dec.Decode(&t2) 2066 if err == nil { 2067 t.Fatal("Decode: did not return error") 2068 } 2069 if t2.Number1 != 1 { 2070 t.Fatal("Decode: did not set Number1") 2071 } 2072 } 2073 2074 // Test that a null for ,string is not replaced with the previous quoted string (issue 7046). 2075 // It should also not be an error (issue 2540, issue 8587). 2076 func TestNullString(t *testing.T) { 2077 type T struct { 2078 A int `json:",string"` 2079 B int `json:",string"` 2080 C *int `json:",string"` 2081 } 2082 data := []byte(`{"A": "1", "B": null, "C": null}`) 2083 var s T 2084 s.B = 1 2085 s.C = new(int) 2086 *s.C = 2 2087 err := json.Unmarshal(data, &s) 2088 if err != nil { 2089 t.Fatalf("Unmarshal: %v", err) 2090 } 2091 if s.B != 1 || s.C != nil { 2092 t.Fatalf("after Unmarshal, s.B=%d, s.C=%p, want 1, nil", s.B, s.C) 2093 } 2094 } 2095 2096 func intp(x int) *int { 2097 p := new(int) 2098 *p = x 2099 return p 2100 } 2101 2102 func intpp(x *int) **int { 2103 pp := new(*int) 2104 *pp = x 2105 return pp 2106 } 2107 2108 var interfaceSetTests = []struct { 2109 pre interface{} 2110 json string 2111 post interface{} 2112 }{ 2113 {"foo", `"bar"`, "bar"}, 2114 {"foo", `2`, 2.0}, 2115 {"foo", `true`, true}, 2116 {"foo", `null`, nil}, 2117 {nil, `null`, nil}, 2118 {new(int), `null`, nil}, 2119 {(*int)(nil), `null`, nil}, 2120 //{new(*int), `null`, new(*int)}, 2121 {(**int)(nil), `null`, nil}, 2122 {intp(1), `null`, nil}, 2123 //{intpp(nil), `null`, intpp(nil)}, 2124 //{intpp(intp(1)), `null`, intpp(nil)}, 2125 } 2126 2127 func TestInterfaceSet(t *testing.T) { 2128 for idx, tt := range interfaceSetTests { 2129 b := struct{ X interface{} }{tt.pre} 2130 blob := `{"X":` + tt.json + `}` 2131 if err := json.Unmarshal([]byte(blob), &b); err != nil { 2132 t.Errorf("Unmarshal %#q: %v", blob, err) 2133 continue 2134 } 2135 if !reflect.DeepEqual(b.X, tt.post) { 2136 t.Errorf("%d: Unmarshal %#q into %#v: X=%#v, want %#v", idx, blob, tt.pre, b.X, tt.post) 2137 } 2138 } 2139 } 2140 2141 // JSON null values should be ignored for primitives and string values instead of resulting in an error. 2142 // Issue 2540 2143 func TestUnmarshalNulls(t *testing.T) { 2144 // Unmarshal docs: 2145 // The JSON null value unmarshals into an interface, map, pointer, or slice 2146 // by setting that Go value to nil. Because null is often used in JSON to mean 2147 // ``not present,'' unmarshaling a JSON null into any other Go type has no effect 2148 // on the value and produces no error. 2149 2150 jsonData := []byte(`{ 2151 "Bool" : null, 2152 "Int" : null, 2153 "Int8" : null, 2154 "Int16" : null, 2155 "Int32" : null, 2156 "Int64" : null, 2157 "Uint" : null, 2158 "Uint8" : null, 2159 "Uint16" : null, 2160 "Uint32" : null, 2161 "Uint64" : null, 2162 "Float32" : null, 2163 "Float64" : null, 2164 "String" : null, 2165 "PBool": null, 2166 "Map": null, 2167 "Slice": null, 2168 "Interface": null, 2169 "PRaw": null, 2170 "PTime": null, 2171 "PBigInt": null, 2172 "PText": null, 2173 "PBuffer": null, 2174 "PStruct": null, 2175 "Raw": null, 2176 "Time": null, 2177 "BigInt": null, 2178 "Text": null, 2179 "Buffer": null, 2180 "Struct": null 2181 }`) 2182 nulls := NullTest{ 2183 Bool: true, 2184 Int: 2, 2185 Int8: 3, 2186 Int16: 4, 2187 Int32: 5, 2188 Int64: 6, 2189 Uint: 7, 2190 Uint8: 8, 2191 Uint16: 9, 2192 Uint32: 10, 2193 Uint64: 11, 2194 Float32: 12.1, 2195 Float64: 13.1, 2196 String: "14", 2197 PBool: new(bool), 2198 Map: map[string]string{}, 2199 Slice: []string{}, 2200 Interface: new(MustNotUnmarshalJSON), 2201 PRaw: new(json.RawMessage), 2202 PTime: new(time.Time), 2203 PBigInt: new(big.Int), 2204 PText: new(MustNotUnmarshalText), 2205 PStruct: new(struct{}), 2206 PBuffer: new(bytes.Buffer), 2207 Raw: json.RawMessage("123"), 2208 Time: time.Unix(123456789, 0), 2209 BigInt: *big.NewInt(123), 2210 } 2211 2212 before := nulls.Time.String() 2213 2214 err := json.Unmarshal(jsonData, &nulls) 2215 if err != nil { 2216 t.Errorf("Unmarshal of null values failed: %v", err) 2217 } 2218 if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 || 2219 nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 || 2220 nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" { 2221 t.Errorf("Unmarshal of null values affected primitives") 2222 } 2223 2224 if nulls.PBool != nil { 2225 t.Errorf("Unmarshal of null did not clear nulls.PBool") 2226 } 2227 if nulls.Map != nil { 2228 t.Errorf("Unmarshal of null did not clear nulls.Map") 2229 } 2230 if nulls.Slice != nil { 2231 t.Errorf("Unmarshal of null did not clear nulls.Slice") 2232 } 2233 if nulls.Interface != nil { 2234 t.Errorf("Unmarshal of null did not clear nulls.Interface") 2235 } 2236 if nulls.PRaw != nil { 2237 t.Errorf("Unmarshal of null did not clear nulls.PRaw") 2238 } 2239 if nulls.PTime != nil { 2240 t.Errorf("Unmarshal of null did not clear nulls.PTime") 2241 } 2242 if nulls.PBigInt != nil { 2243 t.Errorf("Unmarshal of null did not clear nulls.PBigInt") 2244 } 2245 if nulls.PText != nil { 2246 t.Errorf("Unmarshal of null did not clear nulls.PText") 2247 } 2248 if nulls.PBuffer != nil { 2249 t.Errorf("Unmarshal of null did not clear nulls.PBuffer") 2250 } 2251 if nulls.PStruct != nil { 2252 t.Errorf("Unmarshal of null did not clear nulls.PStruct") 2253 } 2254 2255 if string(nulls.Raw) != "null" { 2256 t.Errorf("Unmarshal of RawMessage null did not record null: %v", string(nulls.Raw)) 2257 } 2258 if nulls.Time.String() != before { 2259 t.Errorf("Unmarshal of time.Time null set time to %v", nulls.Time.String()) 2260 } 2261 if nulls.BigInt.String() != "123" { 2262 t.Errorf("Unmarshal of big.Int null set int to %v", nulls.BigInt.String()) 2263 } 2264 } 2265 2266 func TestStringKind(t *testing.T) { 2267 type stringKind string 2268 2269 var m1, m2 map[stringKind]int 2270 m1 = map[stringKind]int{ 2271 "foo": 42, 2272 } 2273 2274 data, err := json.Marshal(m1) 2275 if err != nil { 2276 t.Errorf("Unexpected error marshaling: %v", err) 2277 } 2278 2279 err = json.Unmarshal(data, &m2) 2280 if err != nil { 2281 t.Errorf("Unexpected error unmarshaling: %v", err) 2282 } 2283 2284 if !reflect.DeepEqual(m1, m2) { 2285 t.Error("Items should be equal after encoding and then decoding") 2286 } 2287 } 2288 2289 // Custom types with []byte as underlying type could not be marshaled 2290 // and then unmarshaled. 2291 // Issue 8962. 2292 func TestByteKind(t *testing.T) { 2293 type byteKind []byte 2294 2295 a := byteKind("hello") 2296 2297 data, err := json.Marshal(a) 2298 if err != nil { 2299 t.Error(err) 2300 } 2301 var b byteKind 2302 err = json.Unmarshal(data, &b) 2303 if err != nil { 2304 t.Fatal(err) 2305 } 2306 if !reflect.DeepEqual(a, b) { 2307 t.Errorf("expected %v == %v", a, b) 2308 } 2309 } 2310 2311 // The fix for issue 8962 introduced a regression. 2312 // Issue 12921. 2313 func TestSliceOfCustomByte(t *testing.T) { 2314 type Uint8 uint8 2315 2316 a := []Uint8("hello") 2317 2318 data, err := json.Marshal(a) 2319 if err != nil { 2320 t.Fatal(err) 2321 } 2322 var b []Uint8 2323 err = json.Unmarshal(data, &b) 2324 if err != nil { 2325 t.Fatal(err) 2326 } 2327 if !reflect.DeepEqual(a, b) { 2328 t.Fatalf("expected %v == %v", a, b) 2329 } 2330 } 2331 2332 var decodeTypeErrorTests = []struct { 2333 dest interface{} 2334 src string 2335 }{ 2336 {new(string), `{"user": "name"}`}, // issue 4628. 2337 {new(error), `{}`}, // issue 4222 2338 {new(error), `[]`}, 2339 {new(error), `""`}, 2340 {new(error), `123`}, 2341 {new(error), `true`}, 2342 } 2343 2344 func TestUnmarshalTypeError(t *testing.T) { 2345 for _, item := range decodeTypeErrorTests { 2346 err := json.Unmarshal([]byte(item.src), item.dest) 2347 if _, ok := err.(*json.UnmarshalTypeError); !ok { 2348 t.Errorf("expected type error for Unmarshal(%q, type %T): got %T", 2349 item.src, item.dest, err) 2350 } 2351 } 2352 } 2353 2354 var unmarshalSyntaxTests = []string{ 2355 "tru", 2356 "fals", 2357 "nul", 2358 "123e", 2359 `"hello`, 2360 `[1,2,3`, 2361 `{"key":1`, 2362 `{"key":1,`, 2363 } 2364 2365 func TestUnmarshalSyntax(t *testing.T) { 2366 var x interface{} 2367 for _, src := range unmarshalSyntaxTests { 2368 err := json.Unmarshal([]byte(src), &x) 2369 if _, ok := err.(*json.SyntaxError); !ok { 2370 t.Errorf("expected syntax error for Unmarshal(%q): got %T", src, err) 2371 } 2372 } 2373 } 2374 2375 // Test handling of unexported fields that should be ignored. 2376 // Issue 4660 2377 type unexportedFields struct { 2378 Name string 2379 m map[string]interface{} `json:"-"` 2380 m2 map[string]interface{} `json:"abcd"` 2381 2382 s []int `json:"-"` 2383 } 2384 2385 func TestUnmarshalUnexported(t *testing.T) { 2386 input := `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}, "s": [2, 3]}` 2387 want := &unexportedFields{Name: "Bob"} 2388 2389 out := &unexportedFields{} 2390 err := json.Unmarshal([]byte(input), out) 2391 if err != nil { 2392 t.Errorf("got error %v, expected nil", err) 2393 } 2394 if !reflect.DeepEqual(out, want) { 2395 t.Errorf("got %q, want %q", out, want) 2396 } 2397 } 2398 2399 // Time3339 is a time.Time which encodes to and from JSON 2400 // as an RFC 3339 time in UTC. 2401 type Time3339 time.Time 2402 2403 func (t *Time3339) UnmarshalJSON(b []byte) error { 2404 if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' { 2405 return fmt.Errorf("types: failed to unmarshal non-string value %q as an RFC 3339 time", b) 2406 } 2407 tm, err := time.Parse(time.RFC3339, string(b[1:len(b)-1])) 2408 if err != nil { 2409 return err 2410 } 2411 *t = Time3339(tm) 2412 return nil 2413 } 2414 2415 func TestUnmarshalJSONLiteralError(t *testing.T) { 2416 var t3 Time3339 2417 err := json.Unmarshal([]byte(`"0000-00-00T00:00:00Z"`), &t3) 2418 if err == nil { 2419 t.Fatalf("expected error; got time %v", time.Time(t3)) 2420 } 2421 if !strings.Contains(err.Error(), "range") { 2422 t.Errorf("got err = %v; want out of range error", err) 2423 } 2424 } 2425 2426 // Test that extra object elements in an array do not result in a 2427 // "data changing underfoot" error. 2428 // Issue 3717 2429 func TestSkipArrayObjects(t *testing.T) { 2430 data := `[{}]` 2431 var dest [0]interface{} 2432 2433 err := json.Unmarshal([]byte(data), &dest) 2434 if err != nil { 2435 t.Errorf("got error %q, want nil", err) 2436 } 2437 } 2438 2439 // Test semantics of pre-filled data, such as struct fields, map elements, 2440 // slices, and arrays. 2441 // Issues 4900 and 8837, among others. 2442 func TestPrefilled(t *testing.T) { 2443 // Values here change, cannot reuse table across runs. 2444 var prefillTests = []struct { 2445 in string 2446 ptr interface{} 2447 out interface{} 2448 }{ 2449 { 2450 in: `{"X": 1, "Y": 2}`, 2451 ptr: &XYZ{X: float32(3), Y: int16(4), Z: 1.5}, 2452 out: &XYZ{X: float64(1), Y: float64(2), Z: 1.5}, 2453 }, 2454 { 2455 in: `{"X": 1, "Y": 2}`, 2456 ptr: &map[string]interface{}{"X": float32(3), "Y": int16(4), "Z": 1.5}, 2457 out: &map[string]interface{}{"X": float64(1), "Y": float64(2), "Z": 1.5}, 2458 }, 2459 { 2460 in: `[2]`, 2461 ptr: &[]int{1}, 2462 out: &[]int{2}, 2463 }, 2464 { 2465 in: `[2, 3]`, 2466 ptr: &[]int{1}, 2467 out: &[]int{2, 3}, 2468 }, 2469 { 2470 in: `[2, 3]`, 2471 ptr: &[...]int{1}, 2472 out: &[...]int{2}, 2473 }, 2474 { 2475 in: `[3]`, 2476 ptr: &[...]int{1, 2}, 2477 out: &[...]int{3, 0}, 2478 }, 2479 } 2480 2481 for _, tt := range prefillTests { 2482 ptrstr := fmt.Sprintf("%v", tt.ptr) 2483 err := json.Unmarshal([]byte(tt.in), tt.ptr) // tt.ptr edited here 2484 if err != nil { 2485 t.Errorf("Unmarshal: %v", err) 2486 } 2487 if !reflect.DeepEqual(tt.ptr, tt.out) { 2488 t.Errorf("Unmarshal(%#q, %s): have %v, want %v", tt.in, ptrstr, tt.ptr, tt.out) 2489 } 2490 } 2491 } 2492 2493 var invalidUnmarshalTests = []struct { 2494 v interface{} 2495 want string 2496 }{ 2497 {nil, "json: Unmarshal(nil)"}, 2498 {struct{}{}, "json: Unmarshal(non-pointer struct {})"}, 2499 {(*int)(nil), "json: Unmarshal(nil *int)"}, 2500 } 2501 2502 func TestInvalidUnmarshal(t *testing.T) { 2503 buf := []byte(`{"a":"1"}`) 2504 for _, tt := range invalidUnmarshalTests { 2505 err := json.Unmarshal(buf, tt.v) 2506 if err == nil { 2507 t.Errorf("Unmarshal expecting error, got nil") 2508 continue 2509 } 2510 if got := err.Error(); got != tt.want { 2511 t.Errorf("Unmarshal = %q; want %q", got, tt.want) 2512 } 2513 } 2514 } 2515 2516 var invalidUnmarshalTextTests = []struct { 2517 v interface{} 2518 want string 2519 }{ 2520 {nil, "json: Unmarshal(nil)"}, 2521 {struct{}{}, "json: Unmarshal(non-pointer struct {})"}, 2522 {(*int)(nil), "json: Unmarshal(nil *int)"}, 2523 {new(net.IP), "json: cannot unmarshal number into Go value of type *net.IP"}, 2524 } 2525 2526 func TestInvalidUnmarshalText(t *testing.T) { 2527 buf := []byte(`123`) 2528 for _, tt := range invalidUnmarshalTextTests { 2529 err := json.Unmarshal(buf, tt.v) 2530 if err == nil { 2531 t.Errorf("Unmarshal expecting error, got nil") 2532 continue 2533 } 2534 if got := err.Error(); got != tt.want { 2535 t.Errorf("Unmarshal = %q; want %q", got, tt.want) 2536 } 2537 } 2538 } 2539 2540 // Test that string option is ignored for invalid types. 2541 // Issue 9812. 2542 func TestInvalidStringOption(t *testing.T) { 2543 num := 0 2544 item := struct { 2545 T time.Time `json:",string"` 2546 M map[string]string `json:",string"` 2547 S []string `json:",string"` 2548 A [1]string `json:",string"` 2549 I interface{} `json:",string"` 2550 P *int `json:",string"` 2551 }{M: make(map[string]string), S: make([]string, 0), I: num, P: &num} 2552 2553 data, err := json.Marshal(item) 2554 if err != nil { 2555 t.Fatalf("Marshal: %v", err) 2556 } 2557 err = json.Unmarshal(data, &item) 2558 if err != nil { 2559 t.Fatalf("Unmarshal: %v", err) 2560 } 2561 } 2562 2563 // Test unmarshal behavior with regards to embedded unexported structs. 2564 // 2565 // (Issue 21357) If the embedded struct is a pointer and is unallocated, 2566 // this returns an error because unmarshal cannot set the field. 2567 // 2568 // (Issue 24152) If the embedded struct is given an explicit name, 2569 // ensure that the normal unmarshal logic does not panic in reflect. 2570 // 2571 // (Issue 28145) If the embedded struct is given an explicit name and has 2572 // exported methods, don't cause a panic trying to get its value. 2573 func TestUnmarshalEmbeddedUnexported(t *testing.T) { 2574 type ( 2575 embed1 struct{ Q int } 2576 embed2 struct{ Q int } 2577 embed3 struct { 2578 Q int64 `json:",string"` 2579 } 2580 S1 struct { 2581 *embed1 2582 R int 2583 } 2584 S2 struct { 2585 *embed1 2586 Q int 2587 } 2588 S3 struct { 2589 embed1 2590 R int 2591 } 2592 S4 struct { 2593 *embed1 2594 embed2 2595 } 2596 S5 struct { 2597 *embed3 2598 R int 2599 } 2600 S6 struct { 2601 embed1 `json:"embed1"` 2602 } 2603 S7 struct { 2604 embed1 `json:"embed1"` 2605 embed2 2606 } 2607 S8 struct { 2608 embed1 `json:"embed1"` 2609 embed2 `json:"embed2"` 2610 Q int 2611 } 2612 S9 struct { 2613 unexportedWithMethods `json:"embed"` 2614 } 2615 ) 2616 2617 tests := []struct { 2618 in string 2619 ptr interface{} 2620 out interface{} 2621 err error 2622 }{{ 2623 // Error since we cannot set S1.embed1, but still able to set S1.R. 2624 in: `{"R":2,"Q":1}`, 2625 ptr: new(S1), 2626 out: &S1{R: 2}, 2627 err: fmt.Errorf("json: cannot set embedded pointer to unexported struct: json_test.embed1"), 2628 }, { 2629 // The top level Q field takes precedence. 2630 in: `{"Q":1}`, 2631 ptr: new(S2), 2632 out: &S2{Q: 1}, 2633 }, { 2634 // No issue with non-pointer variant. 2635 in: `{"R":2,"Q":1}`, 2636 ptr: new(S3), 2637 out: &S3{embed1: embed1{Q: 1}, R: 2}, 2638 }, { 2639 // No error since both embedded structs have field R, which annihilate each other. 2640 // Thus, no attempt is made at setting S4.embed1. 2641 in: `{"R":2}`, 2642 ptr: new(S4), 2643 out: new(S4), 2644 }, { 2645 // Error since we cannot set S5.embed1, but still able to set S5.R. 2646 in: `{"R":2,"Q":1}`, 2647 ptr: new(S5), 2648 out: &S5{R: 2}, 2649 err: fmt.Errorf("json: cannot set embedded pointer to unexported struct: json_test.embed3"), 2650 }, { 2651 // Issue 24152, ensure decodeState.indirect does not panic. 2652 in: `{"embed1": {"Q": 1}}`, 2653 ptr: new(S6), 2654 out: &S6{embed1{1}}, 2655 }, { 2656 // Issue 24153, check that we can still set forwarded fields even in 2657 // the presence of a name conflict. 2658 // 2659 // This relies on obscure behavior of reflect where it is possible 2660 // to set a forwarded exported field on an unexported embedded struct 2661 // even though there is a name conflict, even when it would have been 2662 // impossible to do so according to Go visibility rules. 2663 // Go forbids this because it is ambiguous whether S7.Q refers to 2664 // S7.embed1.Q or S7.embed2.Q. Since embed1 and embed2 are unexported, 2665 // it should be impossible for an external package to set either Q. 2666 // 2667 // It is probably okay for a future reflect change to break this. 2668 in: `{"embed1": {"Q": 1}, "Q": 2}`, 2669 ptr: new(S7), 2670 out: &S7{embed1{1}, embed2{2}}, 2671 }, { 2672 // Issue 24153, similar to the S7 case. 2673 in: `{"embed1": {"Q": 1}, "embed2": {"Q": 2}, "Q": 3}`, 2674 ptr: new(S8), 2675 out: &S8{embed1{1}, embed2{2}, 3}, 2676 }, { 2677 // Issue 228145, similar to the cases above. 2678 in: `{"embed": {}}`, 2679 ptr: new(S9), 2680 out: &S9{}, 2681 }} 2682 2683 for i, tt := range tests { 2684 err := json.Unmarshal([]byte(tt.in), tt.ptr) 2685 if !equalError(err, tt.err) { 2686 t.Errorf("#%d: %v, want %v", i, err, tt.err) 2687 } 2688 if !reflect.DeepEqual(tt.ptr, tt.out) { 2689 t.Errorf("#%d: mismatch\ngot: %#+v\nwant: %#+v", i, tt.ptr, tt.out) 2690 } 2691 } 2692 } 2693 2694 func TestUnmarshalErrorAfterMultipleJSON(t *testing.T) { 2695 tests := []struct { 2696 in string 2697 err error 2698 }{{ 2699 in: `1 false null :`, 2700 err: json.NewSyntaxError("invalid character '\x00' looking for beginning of value", 14), 2701 }, { 2702 in: `1 [] [,]`, 2703 err: json.NewSyntaxError("invalid character ',' looking for beginning of value", 6), 2704 }, { 2705 in: `1 [] [true:]`, 2706 err: json.NewSyntaxError("json: slice unexpected end of JSON input", 10), 2707 }, { 2708 in: `1 {} {"x"=}`, 2709 err: json.NewSyntaxError("expected colon after object key", 13), 2710 }, { 2711 in: `falsetruenul#`, 2712 err: json.NewSyntaxError("json: invalid character # as null", 12), 2713 }} 2714 for i, tt := range tests { 2715 dec := json.NewDecoder(strings.NewReader(tt.in)) 2716 var err error 2717 for { 2718 var v interface{} 2719 if err = dec.Decode(&v); err != nil { 2720 break 2721 } 2722 } 2723 if !reflect.DeepEqual(err, tt.err) { 2724 t.Errorf("#%d: got %#v, want %#v", i, err, tt.err) 2725 } 2726 } 2727 } 2728 2729 type unmarshalPanic struct{} 2730 2731 func (unmarshalPanic) UnmarshalJSON([]byte) error { panic(0xdead) } 2732 2733 func TestUnmarshalPanic(t *testing.T) { 2734 defer func() { 2735 if got := recover(); !reflect.DeepEqual(got, 0xdead) { 2736 t.Errorf("panic() = (%T)(%v), want 0xdead", got, got) 2737 } 2738 }() 2739 json.Unmarshal([]byte("{}"), &unmarshalPanic{}) 2740 t.Fatalf("Unmarshal should have panicked") 2741 } 2742 2743 // The decoder used to hang if decoding into an interface pointing to its own address. 2744 // See golang.org/issues/31740. 2745 func TestUnmarshalRecursivePointer(t *testing.T) { 2746 var v interface{} 2747 v = &v 2748 data := []byte(`{"a": "b"}`) 2749 2750 if err := json.Unmarshal(data, v); err != nil { 2751 t.Fatal(err) 2752 } 2753 } 2754 2755 type textUnmarshalerString string 2756 2757 func (m *textUnmarshalerString) UnmarshalText(text []byte) error { 2758 *m = textUnmarshalerString(strings.ToLower(string(text))) 2759 return nil 2760 } 2761 2762 // Test unmarshal to a map, where the map key is a user defined type. 2763 // See golang.org/issues/34437. 2764 func TestUnmarshalMapWithTextUnmarshalerStringKey(t *testing.T) { 2765 var p map[textUnmarshalerString]string 2766 if err := json.Unmarshal([]byte(`{"FOO": "1"}`), &p); err != nil { 2767 t.Fatalf("Unmarshal unexpected error: %v", err) 2768 } 2769 2770 if _, ok := p["foo"]; !ok { 2771 t.Errorf(`Key "foo" does not exist in map: %v`, p) 2772 } 2773 } 2774 2775 func TestUnmarshalRescanLiteralMangledUnquote(t *testing.T) { 2776 // See golang.org/issues/38105. 2777 var p map[textUnmarshalerString]string 2778 if err := json.Unmarshal([]byte(`{"开源":"12345开源"}`), &p); err != nil { 2779 t.Fatalf("Unmarshal unexpected error: %v", err) 2780 } 2781 if _, ok := p["开源"]; !ok { 2782 t.Errorf(`Key "开源" does not exist in map: %v`, p) 2783 } 2784 2785 // See golang.org/issues/38126. 2786 type T struct { 2787 F1 string `json:"F1,string"` 2788 } 2789 t1 := T{"aaa\tbbb"} 2790 2791 b, err := json.Marshal(t1) 2792 if err != nil { 2793 t.Fatalf("Marshal unexpected error: %v", err) 2794 } 2795 var t2 T 2796 if err := json.Unmarshal(b, &t2); err != nil { 2797 t.Fatalf("Unmarshal unexpected error: %v", err) 2798 } 2799 if t1 != t2 { 2800 t.Errorf("Marshal and Unmarshal roundtrip mismatch: want %q got %q", t1, t2) 2801 } 2802 2803 // See golang.org/issues/39555. 2804 input := map[textUnmarshalerString]string{"FOO": "", `"`: ""} 2805 2806 encoded, err := json.Marshal(input) 2807 if err != nil { 2808 t.Fatalf("Marshal unexpected error: %v", err) 2809 } 2810 var got map[textUnmarshalerString]string 2811 if err := json.Unmarshal(encoded, &got); err != nil { 2812 t.Fatalf("Unmarshal unexpected error: %v", err) 2813 } 2814 want := map[textUnmarshalerString]string{"foo": "", `"`: ""} 2815 if !reflect.DeepEqual(want, got) { 2816 t.Fatalf("Unexpected roundtrip result:\nwant: %q\ngot: %q", want, got) 2817 } 2818 } 2819 2820 func TestUnmarshalMaxDepth(t *testing.T) { 2821 testcases := []struct { 2822 name string 2823 data string 2824 errMaxDepth bool 2825 }{ 2826 { 2827 name: "ArrayUnderMaxNestingDepth", 2828 data: `{"a":` + strings.Repeat(`[`, 10000-1) + strings.Repeat(`]`, 10000-1) + `}`, 2829 errMaxDepth: false, 2830 }, 2831 { 2832 name: "ArrayOverMaxNestingDepth", 2833 data: `{"a":` + strings.Repeat(`[`, 10000) + strings.Repeat(`]`, 10000) + `}`, 2834 errMaxDepth: true, 2835 }, 2836 { 2837 name: "ArrayOverStackDepth", 2838 data: `{"a":` + strings.Repeat(`[`, 3000000) + strings.Repeat(`]`, 3000000) + `}`, 2839 errMaxDepth: true, 2840 }, 2841 { 2842 name: "ObjectUnderMaxNestingDepth", 2843 data: `{"a":` + strings.Repeat(`{"a":`, 10000-1) + `0` + strings.Repeat(`}`, 10000-1) + `}`, 2844 errMaxDepth: false, 2845 }, 2846 { 2847 name: "ObjectOverMaxNestingDepth", 2848 data: `{"a":` + strings.Repeat(`{"a":`, 10000) + `0` + strings.Repeat(`}`, 10000) + `}`, 2849 errMaxDepth: true, 2850 }, 2851 { 2852 name: "ObjectOverStackDepth", 2853 data: `{"a":` + strings.Repeat(`{"a":`, 3000000) + `0` + strings.Repeat(`}`, 3000000) + `}`, 2854 errMaxDepth: true, 2855 }, 2856 } 2857 2858 targets := []struct { 2859 name string 2860 newValue func() interface{} 2861 }{ 2862 { 2863 name: "unstructured", 2864 newValue: func() interface{} { 2865 var v interface{} 2866 return &v 2867 }, 2868 }, 2869 { 2870 name: "typed named field", 2871 newValue: func() interface{} { 2872 v := struct { 2873 A interface{} `json:"a"` 2874 }{} 2875 return &v 2876 }, 2877 }, 2878 { 2879 name: "typed missing field", 2880 newValue: func() interface{} { 2881 v := struct { 2882 B interface{} `json:"b"` 2883 }{} 2884 return &v 2885 }, 2886 }, 2887 { 2888 name: "custom unmarshaler", 2889 newValue: func() interface{} { 2890 v := unmarshaler{} 2891 return &v 2892 }, 2893 }, 2894 } 2895 2896 for _, tc := range testcases { 2897 for _, target := range targets { 2898 t.Run(target.name+"-"+tc.name, func(t *testing.T) { 2899 t.Run("unmarshal", func(t *testing.T) { 2900 err := json.Unmarshal([]byte(tc.data), target.newValue()) 2901 if !tc.errMaxDepth { 2902 if err != nil { 2903 t.Errorf("unexpected error: %v", err) 2904 } 2905 } else { 2906 if err == nil { 2907 t.Errorf("expected error containing 'exceeded max depth', got none") 2908 } else if !strings.Contains(err.Error(), "exceeded max depth") { 2909 t.Errorf("expected error containing 'exceeded max depth', got: %v", err) 2910 } 2911 } 2912 }) 2913 t.Run("stream", func(t *testing.T) { 2914 err := json.NewDecoder(strings.NewReader(tc.data)).Decode(target.newValue()) 2915 if !tc.errMaxDepth { 2916 if err != nil { 2917 t.Errorf("unexpected error: %v", err) 2918 } 2919 } else { 2920 if err == nil { 2921 t.Errorf("expected error containing 'exceeded max depth', got none") 2922 } else if !strings.Contains(err.Error(), "exceeded max depth") { 2923 t.Errorf("expected error containing 'exceeded max depth', got: %v", err) 2924 } 2925 } 2926 }) 2927 }) 2928 } 2929 } 2930 } 2931 2932 func TestDecodeSlice(t *testing.T) { 2933 type B struct{ Int int32 } 2934 type A struct{ B *B } 2935 type X struct{ A []*A } 2936 2937 w1 := &X{} 2938 w2 := &X{} 2939 2940 if err := json.Unmarshal([]byte(`{"a": [ {"b":{"int": 42} } ] }`), w1); err != nil { 2941 t.Fatal(err) 2942 } 2943 w1addr := uintptr(unsafe.Pointer(w1.A[0].B)) 2944 2945 if err := json.Unmarshal([]byte(`{"a": [ {"b":{"int": 112} } ] }`), w2); err != nil { 2946 t.Fatal(err) 2947 } 2948 if uintptr(unsafe.Pointer(w1.A[0].B)) != w1addr { 2949 t.Fatal("wrong addr") 2950 } 2951 w2addr := uintptr(unsafe.Pointer(w2.A[0].B)) 2952 if w1addr == w2addr { 2953 t.Fatal("invaid address") 2954 } 2955 } 2956 2957 func TestDecodeMultipleUnmarshal(t *testing.T) { 2958 data := []byte(`[{"AA":{"X":[{"a": "A"},{"b": "B"}],"Y":"y","Z":"z"},"BB":"bb"},{"AA":{"X":[],"Y":"y","Z":"z"},"BB":"bb"}]`) 2959 var a []json.RawMessage 2960 if err := json.Unmarshal(data, &a); err != nil { 2961 t.Fatal(err) 2962 } 2963 if len(a) != 2 { 2964 t.Fatalf("failed to decode: got %v", a) 2965 } 2966 t.Run("first", func(t *testing.T) { 2967 data := a[0] 2968 var v map[string]json.RawMessage 2969 if err := json.Unmarshal(data, &v); err != nil { 2970 t.Fatal(err) 2971 } 2972 if string(v["AA"]) != `{"X":[{"a": "A"},{"b": "B"}],"Y":"y","Z":"z"}` { 2973 t.Fatalf("failed to decode. got %q", v["AA"]) 2974 } 2975 var aa map[string]json.RawMessage 2976 if err := json.Unmarshal(v["AA"], &aa); err != nil { 2977 t.Fatal(err) 2978 } 2979 if string(aa["X"]) != `[{"a": "A"},{"b": "B"}]` { 2980 t.Fatalf("failed to decode. got %q", v["X"]) 2981 } 2982 var x []json.RawMessage 2983 if err := json.Unmarshal(aa["X"], &x); err != nil { 2984 t.Fatal(err) 2985 } 2986 if len(x) != 2 { 2987 t.Fatalf("failed to decode: %v", x) 2988 } 2989 if string(x[0]) != `{"a": "A"}` { 2990 t.Fatal("failed to decode") 2991 } 2992 if string(x[1]) != `{"b": "B"}` { 2993 t.Fatal("failed to decode") 2994 } 2995 }) 2996 t.Run("second", func(t *testing.T) { 2997 data := a[1] 2998 var v map[string]json.RawMessage 2999 if err := json.Unmarshal(data, &v); err != nil { 3000 t.Fatal(err) 3001 } 3002 if string(v["AA"]) != `{"X":[],"Y":"y","Z":"z"}` { 3003 t.Fatalf("failed to decode. got %q", v["AA"]) 3004 } 3005 var aa map[string]json.RawMessage 3006 if err := json.Unmarshal(v["AA"], &aa); err != nil { 3007 t.Fatal(err) 3008 } 3009 if string(aa["X"]) != `[]` { 3010 t.Fatalf("failed to decode. got %q", v["X"]) 3011 } 3012 var x []json.RawMessage 3013 if err := json.Unmarshal(aa["X"], &x); err != nil { 3014 t.Fatal(err) 3015 } 3016 if len(x) != 0 { 3017 t.Fatalf("failed to decode: %v", x) 3018 } 3019 }) 3020 } 3021 3022 func TestMultipleDecodeWithRawMessage(t *testing.T) { 3023 original := []byte(`{ 3024 "Body": { 3025 "List": [ 3026 { 3027 "Returns": [ 3028 { 3029 "Value": "10", 3030 "nodeType": "Literal" 3031 } 3032 ], 3033 "nodeKind": "Return", 3034 "nodeType": "Statement" 3035 } 3036 ], 3037 "nodeKind": "Block", 3038 "nodeType": "Statement" 3039 }, 3040 "nodeType": "Function" 3041 }`) 3042 3043 var a map[string]json.RawMessage 3044 if err := json.Unmarshal(original, &a); err != nil { 3045 t.Fatal(err) 3046 } 3047 var b map[string]json.RawMessage 3048 if err := json.Unmarshal(a["Body"], &b); err != nil { 3049 t.Fatal(err) 3050 } 3051 var c []json.RawMessage 3052 if err := json.Unmarshal(b["List"], &c); err != nil { 3053 t.Fatal(err) 3054 } 3055 var d map[string]json.RawMessage 3056 if err := json.Unmarshal(c[0], &d); err != nil { 3057 t.Fatal(err) 3058 } 3059 var e []json.RawMessage 3060 if err := json.Unmarshal(d["Returns"], &e); err != nil { 3061 t.Fatal(err) 3062 } 3063 var f map[string]json.RawMessage 3064 if err := json.Unmarshal(e[0], &f); err != nil { 3065 t.Fatal(err) 3066 } 3067 } 3068 3069 type intUnmarshaler int 3070 3071 func (u *intUnmarshaler) UnmarshalJSON(b []byte) error { 3072 if *u != 0 && *u != 10 { 3073 return fmt.Errorf("failed to decode of slice with int unmarshaler") 3074 } 3075 *u = 10 3076 return nil 3077 } 3078 3079 type arrayUnmarshaler [5]int 3080 3081 func (u *arrayUnmarshaler) UnmarshalJSON(b []byte) error { 3082 if (*u)[0] != 0 && (*u)[0] != 10 { 3083 return fmt.Errorf("failed to decode of slice with array unmarshaler") 3084 } 3085 (*u)[0] = 10 3086 return nil 3087 } 3088 3089 type mapUnmarshaler map[string]int 3090 3091 func (u *mapUnmarshaler) UnmarshalJSON(b []byte) error { 3092 if len(*u) != 0 && len(*u) != 1 { 3093 return fmt.Errorf("failed to decode of slice with map unmarshaler") 3094 } 3095 *u = map[string]int{"a": 10} 3096 return nil 3097 } 3098 3099 type structUnmarshaler struct { 3100 A int 3101 notFirst bool 3102 } 3103 3104 func (u *structUnmarshaler) UnmarshalJSON(b []byte) error { 3105 if !u.notFirst && u.A != 0 { 3106 return fmt.Errorf("failed to decode of slice with struct unmarshaler") 3107 } 3108 u.A = 10 3109 u.notFirst = true 3110 return nil 3111 } 3112 3113 func TestSliceElemUnmarshaler(t *testing.T) { 3114 t.Run("int", func(t *testing.T) { 3115 var v []intUnmarshaler 3116 if err := json.Unmarshal([]byte(`[1,2,3,4,5]`), &v); err != nil { 3117 t.Fatal(err) 3118 } 3119 if len(v) != 5 { 3120 t.Fatalf("failed to decode of slice with int unmarshaler: %v", v) 3121 } 3122 if v[0] != 10 { 3123 t.Fatalf("failed to decode of slice with int unmarshaler: %v", v) 3124 } 3125 if err := json.Unmarshal([]byte(`[6]`), &v); err != nil { 3126 t.Fatal(err) 3127 } 3128 if len(v) != 1 { 3129 t.Fatalf("failed to decode of slice with int unmarshaler: %v", v) 3130 } 3131 if v[0] != 10 { 3132 t.Fatalf("failed to decode of slice with int unmarshaler: %v", v) 3133 } 3134 }) 3135 t.Run("slice", func(t *testing.T) { 3136 var v []json.RawMessage 3137 if err := json.Unmarshal([]byte(`[1,2,3,4,5]`), &v); err != nil { 3138 t.Fatal(err) 3139 } 3140 if len(v) != 5 { 3141 t.Fatalf("failed to decode of slice with slice unmarshaler: %v", v) 3142 } 3143 if len(v[0]) != 1 { 3144 t.Fatalf("failed to decode of slice with slice unmarshaler: %v", v) 3145 } 3146 if err := json.Unmarshal([]byte(`[6]`), &v); err != nil { 3147 t.Fatal(err) 3148 } 3149 if len(v) != 1 { 3150 t.Fatalf("failed to decode of slice with slice unmarshaler: %v", v) 3151 } 3152 if len(v[0]) != 1 { 3153 t.Fatalf("failed to decode of slice with slice unmarshaler: %v", v) 3154 } 3155 }) 3156 t.Run("array", func(t *testing.T) { 3157 var v []arrayUnmarshaler 3158 if err := json.Unmarshal([]byte(`[1,2,3,4,5]`), &v); err != nil { 3159 t.Fatal(err) 3160 } 3161 if len(v) != 5 { 3162 t.Fatalf("failed to decode of slice with array unmarshaler: %v", v) 3163 } 3164 if v[0][0] != 10 { 3165 t.Fatalf("failed to decode of slice with array unmarshaler: %v", v) 3166 } 3167 if err := json.Unmarshal([]byte(`[6]`), &v); err != nil { 3168 t.Fatal(err) 3169 } 3170 if len(v) != 1 { 3171 t.Fatalf("failed to decode of slice with array unmarshaler: %v", v) 3172 } 3173 if v[0][0] != 10 { 3174 t.Fatalf("failed to decode of slice with array unmarshaler: %v", v) 3175 } 3176 }) 3177 t.Run("map", func(t *testing.T) { 3178 var v []mapUnmarshaler 3179 if err := json.Unmarshal([]byte(`[{"a":1},{"b":2},{"c":3},{"d":4},{"e":5}]`), &v); err != nil { 3180 t.Fatal(err) 3181 } 3182 if len(v) != 5 { 3183 t.Fatalf("failed to decode of slice with map unmarshaler: %v", v) 3184 } 3185 if v[0]["a"] != 10 { 3186 t.Fatalf("failed to decode of slice with map unmarshaler: %v", v) 3187 } 3188 if err := json.Unmarshal([]byte(`[6]`), &v); err != nil { 3189 t.Fatal(err) 3190 } 3191 if len(v) != 1 { 3192 t.Fatalf("failed to decode of slice with map unmarshaler: %v", v) 3193 } 3194 if v[0]["a"] != 10 { 3195 t.Fatalf("failed to decode of slice with map unmarshaler: %v", v) 3196 } 3197 }) 3198 t.Run("struct", func(t *testing.T) { 3199 var v []structUnmarshaler 3200 if err := json.Unmarshal([]byte(`[1,2,3,4,5]`), &v); err != nil { 3201 t.Fatal(err) 3202 } 3203 if len(v) != 5 { 3204 t.Fatalf("failed to decode of slice with struct unmarshaler: %v", v) 3205 } 3206 if v[0].A != 10 { 3207 t.Fatalf("failed to decode of slice with struct unmarshaler: %v", v) 3208 } 3209 if err := json.Unmarshal([]byte(`[6]`), &v); err != nil { 3210 t.Fatal(err) 3211 } 3212 if len(v) != 1 { 3213 t.Fatalf("failed to decode of slice with struct unmarshaler: %v", v) 3214 } 3215 if v[0].A != 10 { 3216 t.Fatalf("failed to decode of slice with struct unmarshaler: %v", v) 3217 } 3218 }) 3219 } 3220 3221 type keepRefTest struct { 3222 A int 3223 B string 3224 } 3225 3226 func (t *keepRefTest) UnmarshalJSON(data []byte) error { 3227 v := []interface{}{&t.A, &t.B} 3228 return json.Unmarshal(data, &v) 3229 } 3230 3231 func TestKeepReferenceSlice(t *testing.T) { 3232 var v keepRefTest 3233 if err := json.Unmarshal([]byte(`[54,"hello"]`), &v); err != nil { 3234 t.Fatal(err) 3235 } 3236 if v.A != 54 { 3237 t.Fatal("failed to keep reference for slice") 3238 } 3239 if v.B != "hello" { 3240 t.Fatal("failed to keep reference for slice") 3241 } 3242 } 3243 3244 func TestInvalidTopLevelValue(t *testing.T) { 3245 t.Run("invalid end of buffer", func(t *testing.T) { 3246 var v struct{} 3247 if err := stdjson.Unmarshal([]byte(`{}0`), &v); err == nil { 3248 t.Fatal("expected error") 3249 } 3250 if err := json.Unmarshal([]byte(`{}0`), &v); err == nil { 3251 t.Fatal("expected error") 3252 } 3253 }) 3254 t.Run("invalid object", func(t *testing.T) { 3255 var v interface{} 3256 if err := stdjson.Unmarshal([]byte(`{"a":4}{"a"5}`), &v); err == nil { 3257 t.Fatal("expected error") 3258 } 3259 if err := json.Unmarshal([]byte(`{"a":4}{"a"5}`), &v); err == nil { 3260 t.Fatal("expected error") 3261 } 3262 }) 3263 } 3264 3265 func TestInvalidNumber(t *testing.T) { 3266 t.Run("invalid length of number", func(t *testing.T) { 3267 invalidNum := strings.Repeat("1", 30) 3268 t.Run("int", func(t *testing.T) { 3269 var v int64 3270 stdErr := stdjson.Unmarshal([]byte(invalidNum), &v) 3271 if stdErr == nil { 3272 t.Fatal("expected error") 3273 } 3274 err := json.Unmarshal([]byte(invalidNum), &v) 3275 if err == nil { 3276 t.Fatal("expected error") 3277 } 3278 if stdErr.Error() != err.Error() { 3279 t.Fatalf("unexpected error message. expected: %q but got %q", stdErr.Error(), err.Error()) 3280 } 3281 }) 3282 t.Run("uint", func(t *testing.T) { 3283 var v uint64 3284 stdErr := stdjson.Unmarshal([]byte(invalidNum), &v) 3285 if stdErr == nil { 3286 t.Fatal("expected error") 3287 } 3288 err := json.Unmarshal([]byte(invalidNum), &v) 3289 if err == nil { 3290 t.Fatal("expected error") 3291 } 3292 if stdErr.Error() != err.Error() { 3293 t.Fatalf("unexpected error message. expected: %q but got %q", stdErr.Error(), err.Error()) 3294 } 3295 }) 3296 3297 }) 3298 t.Run("invalid number of zero", func(t *testing.T) { 3299 t.Run("int", func(t *testing.T) { 3300 invalidNum := strings.Repeat("0", 10) 3301 var v int64 3302 stdErr := stdjson.Unmarshal([]byte(invalidNum), &v) 3303 if stdErr == nil { 3304 t.Fatal("expected error") 3305 } 3306 err := json.Unmarshal([]byte(invalidNum), &v) 3307 if err == nil { 3308 t.Fatal("expected error") 3309 } 3310 if stdErr.Error() != err.Error() { 3311 t.Fatalf("unexpected error message. expected: %q but got %q", stdErr.Error(), err.Error()) 3312 } 3313 }) 3314 t.Run("uint", func(t *testing.T) { 3315 invalidNum := strings.Repeat("0", 10) 3316 var v uint64 3317 stdErr := stdjson.Unmarshal([]byte(invalidNum), &v) 3318 if stdErr == nil { 3319 t.Fatal("expected error") 3320 } 3321 err := json.Unmarshal([]byte(invalidNum), &v) 3322 if err == nil { 3323 t.Fatal("expected error") 3324 } 3325 if stdErr.Error() != err.Error() { 3326 t.Fatalf("unexpected error message. expected: %q but got %q", stdErr.Error(), err.Error()) 3327 } 3328 }) 3329 }) 3330 t.Run("invalid number", func(t *testing.T) { 3331 t.Run("int", func(t *testing.T) { 3332 t.Run("-0", func(t *testing.T) { 3333 var v int64 3334 if err := stdjson.Unmarshal([]byte(`-0`), &v); err != nil { 3335 t.Fatal(err) 3336 } 3337 if err := json.Unmarshal([]byte(`-0`), &v); err != nil { 3338 t.Fatal(err) 3339 } 3340 }) 3341 t.Run("+0", func(t *testing.T) { 3342 var v int64 3343 if err := stdjson.Unmarshal([]byte(`+0`), &v); err == nil { 3344 t.Error("expected error") 3345 } 3346 if err := json.Unmarshal([]byte(`+0`), &v); err == nil { 3347 t.Error("expected error") 3348 } 3349 }) 3350 }) 3351 t.Run("uint", func(t *testing.T) { 3352 t.Run("-0", func(t *testing.T) { 3353 var v uint64 3354 if err := stdjson.Unmarshal([]byte(`-0`), &v); err == nil { 3355 t.Error("expected error") 3356 } 3357 if err := json.Unmarshal([]byte(`-0`), &v); err == nil { 3358 t.Error("expected error") 3359 } 3360 }) 3361 t.Run("+0", func(t *testing.T) { 3362 var v uint64 3363 if err := stdjson.Unmarshal([]byte(`+0`), &v); err == nil { 3364 t.Error("expected error") 3365 } 3366 if err := json.Unmarshal([]byte(`+0`), &v); err == nil { 3367 t.Error("expected error") 3368 } 3369 }) 3370 }) 3371 t.Run("float", func(t *testing.T) { 3372 t.Run("0.0", func(t *testing.T) { 3373 var f float64 3374 if err := stdjson.Unmarshal([]byte(`0.0`), &f); err != nil { 3375 t.Fatal(err) 3376 } 3377 if err := json.Unmarshal([]byte(`0.0`), &f); err != nil { 3378 t.Fatal(err) 3379 } 3380 }) 3381 t.Run("0.000000000", func(t *testing.T) { 3382 var f float64 3383 if err := stdjson.Unmarshal([]byte(`0.000000000`), &f); err != nil { 3384 t.Fatal(err) 3385 } 3386 if err := json.Unmarshal([]byte(`0.000000000`), &f); err != nil { 3387 t.Fatal(err) 3388 } 3389 }) 3390 t.Run("repeat zero a lot with float value", func(t *testing.T) { 3391 var f float64 3392 if err := stdjson.Unmarshal([]byte("0."+strings.Repeat("0", 30)), &f); err != nil { 3393 t.Fatal(err) 3394 } 3395 if err := json.Unmarshal([]byte("0."+strings.Repeat("0", 30)), &f); err != nil { 3396 t.Fatal(err) 3397 } 3398 }) 3399 }) 3400 }) 3401 } 3402 3403 type someInterface interface { 3404 DoesNotMatter() 3405 } 3406 3407 func TestDecodeUnknownInterface(t *testing.T) { 3408 t.Run("unmarshal", func(t *testing.T) { 3409 var v map[string]someInterface 3410 if err := json.Unmarshal([]byte(`{"a":null,"b":null}`), &v); err != nil { 3411 t.Fatal(err) 3412 } 3413 if len(v) != 2 { 3414 t.Fatalf("failed to decode: %v", v) 3415 } 3416 if a, exists := v["a"]; a != nil || !exists { 3417 t.Fatalf("failed to decode: %v", v) 3418 } 3419 if b, exists := v["b"]; b != nil || !exists { 3420 t.Fatalf("failed to decode: %v", v) 3421 } 3422 }) 3423 t.Run("stream", func(t *testing.T) { 3424 var v map[string]someInterface 3425 if err := json.NewDecoder(strings.NewReader(`{"a":null,"b":null}`)).Decode(&v); err != nil { 3426 t.Fatal(err) 3427 } 3428 if len(v) != 2 { 3429 t.Fatalf("failed to decode: %v", v) 3430 } 3431 if a, exists := v["a"]; a != nil || !exists { 3432 t.Fatalf("failed to decode: %v", v) 3433 } 3434 if b, exists := v["b"]; b != nil || !exists { 3435 t.Fatalf("failed to decode: %v", v) 3436 } 3437 }) 3438 } 3439 3440 func TestDecodeByteSliceNull(t *testing.T) { 3441 t.Run("unmarshal", func(t *testing.T) { 3442 var v1 []byte 3443 if err := stdjson.Unmarshal([]byte(`null`), &v1); err != nil { 3444 t.Fatal(err) 3445 } 3446 var v2 []byte 3447 if err := json.Unmarshal([]byte(`null`), &v2); err != nil { 3448 t.Fatal(err) 3449 } 3450 if v1 == nil && v2 != nil || len(v1) != len(v2) { 3451 t.Fatalf("failed to decode null to []byte. expected:%#v but got %#v", v1, v2) 3452 } 3453 }) 3454 t.Run("stream", func(t *testing.T) { 3455 var v1 []byte 3456 if err := stdjson.NewDecoder(strings.NewReader(`null`)).Decode(&v1); err != nil { 3457 t.Fatal(err) 3458 } 3459 var v2 []byte 3460 if err := json.NewDecoder(strings.NewReader(`null`)).Decode(&v2); err != nil { 3461 t.Fatal(err) 3462 } 3463 if v1 == nil && v2 != nil || len(v1) != len(v2) { 3464 t.Fatalf("failed to decode null to []byte. expected:%#v but got %#v", v1, v2) 3465 } 3466 }) 3467 } 3468 3469 func TestDecodeBackSlash(t *testing.T) { 3470 t.Run("unmarshal", func(t *testing.T) { 3471 t.Run("string", func(t *testing.T) { 3472 var v1 map[string]stdjson.RawMessage 3473 if err := stdjson.Unmarshal([]byte(`{"c":"\\"}`), &v1); err != nil { 3474 t.Fatal(err) 3475 } 3476 var v2 map[string]json.RawMessage 3477 if err := json.Unmarshal([]byte(`{"c":"\\"}`), &v2); err != nil { 3478 t.Fatal(err) 3479 } 3480 if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) { 3481 t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2) 3482 } 3483 }) 3484 t.Run("array", func(t *testing.T) { 3485 var v1 map[string]stdjson.RawMessage 3486 if err := stdjson.Unmarshal([]byte(`{"c":["\\"]}`), &v1); err != nil { 3487 t.Fatal(err) 3488 } 3489 var v2 map[string]json.RawMessage 3490 if err := json.Unmarshal([]byte(`{"c":["\\"]}`), &v2); err != nil { 3491 t.Fatal(err) 3492 } 3493 if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) { 3494 t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2) 3495 } 3496 }) 3497 t.Run("object", func(t *testing.T) { 3498 var v1 map[string]stdjson.RawMessage 3499 if err := stdjson.Unmarshal([]byte(`{"c":{"\\":"\\"}}`), &v1); err != nil { 3500 t.Fatal(err) 3501 } 3502 var v2 map[string]json.RawMessage 3503 if err := json.Unmarshal([]byte(`{"c":{"\\":"\\"}}`), &v2); err != nil { 3504 t.Fatal(err) 3505 } 3506 if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) { 3507 t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2) 3508 } 3509 }) 3510 }) 3511 t.Run("stream", func(t *testing.T) { 3512 t.Run("string", func(t *testing.T) { 3513 var v1 map[string]stdjson.RawMessage 3514 if err := stdjson.NewDecoder(strings.NewReader(`{"c":"\\"}`)).Decode(&v1); err != nil { 3515 t.Fatal(err) 3516 } 3517 var v2 map[string]json.RawMessage 3518 if err := json.NewDecoder(strings.NewReader(`{"c":"\\"}`)).Decode(&v2); err != nil { 3519 t.Fatal(err) 3520 } 3521 if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) { 3522 t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2) 3523 } 3524 }) 3525 t.Run("array", func(t *testing.T) { 3526 var v1 map[string]stdjson.RawMessage 3527 if err := stdjson.NewDecoder(strings.NewReader(`{"c":["\\"]}`)).Decode(&v1); err != nil { 3528 t.Fatal(err) 3529 } 3530 var v2 map[string]json.RawMessage 3531 if err := json.NewDecoder(strings.NewReader(`{"c":["\\"]}`)).Decode(&v2); err != nil { 3532 t.Fatal(err) 3533 } 3534 if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) { 3535 t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2) 3536 } 3537 }) 3538 t.Run("object", func(t *testing.T) { 3539 var v1 map[string]stdjson.RawMessage 3540 if err := stdjson.NewDecoder(strings.NewReader(`{"c":{"\\":"\\"}}`)).Decode(&v1); err != nil { 3541 t.Fatal(err) 3542 } 3543 var v2 map[string]json.RawMessage 3544 if err := json.NewDecoder(strings.NewReader(`{"c":{"\\":"\\"}}`)).Decode(&v2); err != nil { 3545 t.Fatal(err) 3546 } 3547 if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) { 3548 t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2) 3549 } 3550 }) 3551 }) 3552 } 3553 3554 func TestIssue218(t *testing.T) { 3555 type A struct { 3556 X int 3557 } 3558 type B struct { 3559 Y int 3560 } 3561 type S struct { 3562 A *A `json:"a,omitempty"` 3563 B *B `json:"b,omitempty"` 3564 } 3565 tests := []struct { 3566 name string 3567 given []S 3568 expected []S 3569 }{ 3570 { 3571 name: "A should be correct", 3572 given: []S{{ 3573 A: &A{ 3574 X: 1, 3575 }, 3576 }}, 3577 expected: []S{{ 3578 A: &A{ 3579 X: 1, 3580 }, 3581 }}, 3582 }, 3583 { 3584 name: "B should be correct", 3585 given: []S{{ 3586 B: &B{ 3587 Y: 2, 3588 }, 3589 }}, 3590 expected: []S{{ 3591 B: &B{ 3592 Y: 2, 3593 }, 3594 }}, 3595 }, 3596 } 3597 for _, test := range tests { 3598 test := test 3599 t.Run(test.name, func(t *testing.T) { 3600 var buf bytes.Buffer 3601 if err := json.NewEncoder(&buf).Encode(test.given); err != nil { 3602 t.Fatal(err) 3603 } 3604 var actual []S 3605 if err := json.NewDecoder(bytes.NewReader(buf.Bytes())).Decode(&actual); err != nil { 3606 t.Fatal(err) 3607 } 3608 if !reflect.DeepEqual(test.expected, actual) { 3609 t.Fatalf("mismatch value: expected %v but got %v", test.expected, actual) 3610 } 3611 }) 3612 } 3613 } 3614 3615 func TestDecodeEscapedCharField(t *testing.T) { 3616 b := []byte(`{"\u6D88\u606F":"\u6D88\u606F"}`) 3617 t.Run("unmarshal", func(t *testing.T) { 3618 v := struct { 3619 Msg string `json:"消息"` 3620 }{} 3621 if err := json.Unmarshal(b, &v); err != nil { 3622 t.Fatal(err) 3623 } 3624 if !bytes.Equal([]byte(v.Msg), []byte("消息")) { 3625 t.Fatal("failed to decode unicode char") 3626 } 3627 }) 3628 t.Run("stream", func(t *testing.T) { 3629 v := struct { 3630 Msg string `json:"消息"` 3631 }{} 3632 if err := json.NewDecoder(bytes.NewBuffer(b)).Decode(&v); err != nil { 3633 t.Fatal(err) 3634 } 3635 if !bytes.Equal([]byte(v.Msg), []byte("消息")) { 3636 t.Fatal("failed to decode unicode char") 3637 } 3638 }) 3639 } 3640 3641 type unmarshalContextKey struct{} 3642 3643 type unmarshalContextStructType struct { 3644 v int 3645 } 3646 3647 func (t *unmarshalContextStructType) UnmarshalJSON(ctx context.Context, b []byte) error { 3648 v := ctx.Value(unmarshalContextKey{}) 3649 s, ok := v.(string) 3650 if !ok { 3651 return fmt.Errorf("failed to propagate parent context.Context") 3652 } 3653 if s != "hello" { 3654 return fmt.Errorf("failed to propagate parent context.Context") 3655 } 3656 t.v = 100 3657 return nil 3658 } 3659 3660 func TestDecodeContextOption(t *testing.T) { 3661 src := []byte("10") 3662 buf := bytes.NewBuffer(src) 3663 3664 t.Run("UnmarshalContext", func(t *testing.T) { 3665 ctx := context.WithValue(context.Background(), unmarshalContextKey{}, "hello") 3666 var v unmarshalContextStructType 3667 if err := json.UnmarshalContext(ctx, src, &v); err != nil { 3668 t.Fatal(err) 3669 } 3670 if v.v != 100 { 3671 t.Fatal("failed to decode with context") 3672 } 3673 }) 3674 t.Run("DecodeContext", func(t *testing.T) { 3675 ctx := context.WithValue(context.Background(), unmarshalContextKey{}, "hello") 3676 var v unmarshalContextStructType 3677 if err := json.NewDecoder(buf).DecodeContext(ctx, &v); err != nil { 3678 t.Fatal(err) 3679 } 3680 if v.v != 100 { 3681 t.Fatal("failed to decode with context") 3682 } 3683 }) 3684 } 3685 3686 func TestIssue251(t *testing.T) { 3687 array := [3]int{1, 2, 3} 3688 err := stdjson.Unmarshal([]byte("[ ]"), &array) 3689 if err != nil { 3690 t.Fatal(err) 3691 } 3692 t.Log(array) 3693 3694 array = [3]int{1, 2, 3} 3695 err = json.Unmarshal([]byte("[ ]"), &array) 3696 if err != nil { 3697 t.Fatal(err) 3698 } 3699 t.Log(array) 3700 3701 array = [3]int{1, 2, 3} 3702 err = json.NewDecoder(strings.NewReader(`[ ]`)).Decode(&array) 3703 if err != nil { 3704 t.Fatal(err) 3705 } 3706 t.Log(array) 3707 } 3708 3709 func TestDecodeBinaryTypeWithEscapedChar(t *testing.T) { 3710 type T struct { 3711 Msg []byte `json:"msg"` 3712 } 3713 content := []byte(`{"msg":"aGVsbG8K\n"}`) 3714 t.Run("unmarshal", func(t *testing.T) { 3715 var expected T 3716 if err := stdjson.Unmarshal(content, &expected); err != nil { 3717 t.Fatal(err) 3718 } 3719 var got T 3720 if err := json.Unmarshal(content, &got); err != nil { 3721 t.Fatal(err) 3722 } 3723 if !bytes.Equal(expected.Msg, got.Msg) { 3724 t.Fatalf("failed to decode binary type with escaped char. expected %q but got %q", expected.Msg, got.Msg) 3725 } 3726 }) 3727 t.Run("stream", func(t *testing.T) { 3728 var expected T 3729 if err := stdjson.NewDecoder(bytes.NewBuffer(content)).Decode(&expected); err != nil { 3730 t.Fatal(err) 3731 } 3732 var got T 3733 if err := json.NewDecoder(bytes.NewBuffer(content)).Decode(&got); err != nil { 3734 t.Fatal(err) 3735 } 3736 if !bytes.Equal(expected.Msg, got.Msg) { 3737 t.Fatalf("failed to decode binary type with escaped char. expected %q but got %q", expected.Msg, got.Msg) 3738 } 3739 }) 3740 } 3741 3742 func TestIssue282(t *testing.T) { 3743 var J = []byte(`{ 3744 "a": {}, 3745 "b": {}, 3746 "c": {}, 3747 "d": {}, 3748 "e": {}, 3749 "f": {}, 3750 "g": {}, 3751 "h": { 3752 "m": "1" 3753 }, 3754 "i": {} 3755 }`) 3756 3757 type T4 struct { 3758 F0 string 3759 F1 string 3760 F2 string 3761 F3 string 3762 F4 string 3763 F5 string 3764 F6 int 3765 } 3766 type T3 struct { 3767 F0 string 3768 F1 T4 3769 } 3770 type T2 struct { 3771 F0 string `json:"m"` 3772 F1 T3 3773 } 3774 type T0 map[string]T2 3775 3776 // T2 size is 136 bytes. This is indirect type. 3777 var v T0 3778 if err := json.Unmarshal(J, &v); err != nil { 3779 t.Fatal(err) 3780 } 3781 if v["h"].F0 != "1" { 3782 t.Fatalf("failed to assign map value") 3783 } 3784 } 3785 3786 func TestDecodeStructFieldMap(t *testing.T) { 3787 type Foo struct { 3788 Bar map[float64]float64 `json:"bar,omitempty"` 3789 } 3790 var v Foo 3791 if err := json.Unmarshal([]byte(`{"name":"test"}`), &v); err != nil { 3792 t.Fatal(err) 3793 } 3794 if v.Bar != nil { 3795 t.Fatalf("failed to decode v.Bar = %+v", v.Bar) 3796 } 3797 } 3798 3799 type issue303 struct { 3800 Count int 3801 Type string 3802 Value interface{} 3803 } 3804 3805 func (t *issue303) UnmarshalJSON(b []byte) error { 3806 type tmpType issue303 3807 3808 wrapped := struct { 3809 Value json.RawMessage 3810 tmpType 3811 }{} 3812 if err := json.Unmarshal(b, &wrapped); err != nil { 3813 return err 3814 } 3815 *t = issue303(wrapped.tmpType) 3816 3817 switch wrapped.Type { 3818 case "string": 3819 var str string 3820 if err := json.Unmarshal(wrapped.Value, &str); err != nil { 3821 return err 3822 } 3823 t.Value = str 3824 } 3825 return nil 3826 } 3827 3828 func TestIssue303(t *testing.T) { 3829 var v issue303 3830 if err := json.Unmarshal([]byte(`{"Count":7,"Type":"string","Value":"hello"}`), &v); err != nil { 3831 t.Fatal(err) 3832 } 3833 if v.Count != 7 || v.Type != "string" || v.Value != "hello" { 3834 t.Fatalf("failed to decode. count = %d type = %s value = %v", v.Count, v.Type, v.Value) 3835 } 3836 } 3837 3838 func TestIssue327(t *testing.T) { 3839 var v struct { 3840 Date time.Time `json:"date"` 3841 } 3842 dec := json.NewDecoder(strings.NewReader(`{"date": "2021-11-23T13:47:30+01:00"})`)) 3843 if err := dec.DecodeContext(context.Background(), &v); err != nil { 3844 t.Fatal(err) 3845 } 3846 expected := "2021-11-23T13:47:30+01:00" 3847 if got := v.Date.Format(time.RFC3339); got != expected { 3848 t.Fatalf("failed to decode. expected %q but got %q", expected, got) 3849 } 3850 } 3851 3852 func TestIssue337(t *testing.T) { 3853 in := strings.Repeat(" ", 510) + "{}" 3854 var m map[string]string 3855 if err := json.NewDecoder(strings.NewReader(in)).Decode(&m); err != nil { 3856 t.Fatal("unexpected error:", err) 3857 } 3858 if len(m) != 0 { 3859 t.Fatal("unexpected result", m) 3860 } 3861 } 3862 3863 func Benchmark306(b *testing.B) { 3864 type T0 struct { 3865 Str string 3866 } 3867 in := []byte(`{"Str":"` + strings.Repeat(`abcd\"`, 10000) + `"}`) 3868 b.Run("stdjson", func(b *testing.B) { 3869 var x T0 3870 for i := 0; i < b.N; i++ { 3871 stdjson.Unmarshal(in, &x) 3872 } 3873 }) 3874 b.Run("go-json", func(b *testing.B) { 3875 var x T0 3876 for i := 0; i < b.N; i++ { 3877 json.Unmarshal(in, &x) 3878 } 3879 }) 3880 } 3881 3882 func TestIssue348(t *testing.T) { 3883 in := strings.Repeat("["+strings.Repeat(",1000", 500)[1:]+"]", 2) 3884 dec := json.NewDecoder(strings.NewReader(in)) 3885 for dec.More() { 3886 var foo interface{} 3887 if err := dec.Decode(&foo); err != nil { 3888 t.Error(err) 3889 } 3890 } 3891 } 3892 3893 type issue342 string 3894 3895 func (t *issue342) UnmarshalJSON(b []byte) error { 3896 panic("unreachable") 3897 } 3898 3899 func TestIssue342(t *testing.T) { 3900 var v map[issue342]int 3901 in := []byte(`{"a":1}`) 3902 if err := json.Unmarshal(in, &v); err != nil { 3903 t.Errorf("unexpected error: %v", err) 3904 } 3905 expected := 1 3906 if got := v["a"]; got != expected { 3907 t.Errorf("unexpected result: got(%v) != expected(%v)", got, expected) 3908 } 3909 } 3910 3911 func TestIssue360(t *testing.T) { 3912 var uints []uint8 3913 err := json.Unmarshal([]byte(`[0, 1, 2]`), &uints) 3914 if err != nil { 3915 t.Errorf("unexpected error: %v", err) 3916 } 3917 if len(uints) != 3 || !(uints[0] == 0 && uints[1] == 1 && uints[2] == 2) { 3918 t.Errorf("unexpected result: %v", uints) 3919 } 3920 } 3921 3922 func TestIssue359(t *testing.T) { 3923 var a interface{} = 1 3924 var b interface{} = &a 3925 var c interface{} = &b 3926 v, err := json.Marshal(c) 3927 if err != nil { 3928 t.Errorf("unexpected error: %v", err) 3929 } 3930 if string(v) != "1" { 3931 t.Errorf("unexpected result: %v", string(v)) 3932 } 3933 } 3934 3935 func TestIssue364(t *testing.T) { 3936 var v struct { 3937 Description string `json:"description"` 3938 } 3939 err := json.Unmarshal([]byte(`{"description":"\uD83D\uDE87 Toledo is a metro station"}`), &v) 3940 if err != nil { 3941 t.Errorf("unexpected error: %v", err) 3942 } 3943 if v.Description != "🚇 Toledo is a metro station" { 3944 t.Errorf("unexpected result: %v", v.Description) 3945 } 3946 } 3947 3948 func TestIssue362(t *testing.T) { 3949 type AliasedPrimitive int 3950 type Combiner struct { 3951 SomeField int 3952 AliasedPrimitive 3953 } 3954 originalCombiner := Combiner{AliasedPrimitive: 7} 3955 b, err := json.Marshal(originalCombiner) 3956 assertErr(t, err) 3957 newCombiner := Combiner{} 3958 err = json.Unmarshal(b, &newCombiner) 3959 assertErr(t, err) 3960 assertEq(t, "TestEmbeddedPrimitiveAlias", originalCombiner, newCombiner) 3961 } 3962 3963 func TestIssue335(t *testing.T) { 3964 var v []string 3965 in := []byte(`["\u","A"]`) 3966 err := json.Unmarshal(in, &v) 3967 if err == nil { 3968 t.Errorf("unexpected success") 3969 } 3970 } 3971 3972 func TestIssue372(t *testing.T) { 3973 type A int 3974 type T struct { 3975 _ int 3976 *A 3977 } 3978 var v T 3979 err := json.Unmarshal([]byte(`{"A":7}`), &v) 3980 assertErr(t, err) 3981 3982 got := *v.A 3983 expected := A(7) 3984 if got != expected { 3985 t.Errorf("unexpected result: %v != %v", got, expected) 3986 } 3987 } 3988 3989 type issue384 struct{} 3990 3991 func (t *issue384) UnmarshalJSON(b []byte) error { 3992 return nil 3993 } 3994 3995 func TestIssue384(t *testing.T) { 3996 testcases := []string{ 3997 `{"data": "` + strings.Repeat("-", 500) + `\""}`, 3998 `["` + strings.Repeat("-", 508) + `\""]`, 3999 } 4000 for _, tc := range testcases { 4001 dec := json.NewDecoder(strings.NewReader(tc)) 4002 var v issue384 4003 if err := dec.Decode(&v); err != nil { 4004 t.Errorf("unexpected error: %v", err) 4005 } 4006 } 4007 }