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