1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
30 Alphabet
string `json:"alpha"`
44 // ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and
46 var ifaceNumAsFloat64
= map[string]interface{}{
49 "k3": []interface{}{float64(1), float64(2.0), float64(3e-3)},
50 "k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)},
53 var ifaceNumAsNumber
= map[string]interface{}{
56 "k3": []interface{}{Number("1"), Number("2.0"), Number("3e-3")},
57 "k4": map[string]interface{}{"kk1": "s", "kk2": Number("2")},
66 // A type that can unmarshal itself.
68 type unmarshaler
struct {
72 func (u
*unmarshaler
) UnmarshalJSON(b
[]byte) error
{
73 *u
= unmarshaler
{true} // All we need to see that UnmarshalJSON is called.
81 type unmarshalerText
struct {
85 // needed for re-marshaling tests
86 func (u unmarshalerText
) MarshalText() ([]byte, error
) {
87 return []byte(u
.A
+ ":" + u
.B
), nil
90 func (u
*unmarshalerText
) UnmarshalText(b
[]byte) error
{
91 pos
:= bytes
.IndexByte(b
, ':')
93 return errors
.New("missing separator")
95 u
.A
, u
.B
= string(b
[:pos
]), string(b
[pos
+1:])
99 var _ encoding
.TextUnmarshaler
= (*unmarshalerText
)(nil)
101 type ustructText
struct {
105 // u8marshal is an integer type that can marshal/unmarshal itself.
108 func (u8 u8marshal
) MarshalText() ([]byte, error
) {
109 return []byte(fmt
.Sprintf("u%d", u8
)), nil
112 var errMissingU8Prefix
= errors
.New("missing 'u' prefix")
114 func (u8
*u8marshal
) UnmarshalText(b
[]byte) error
{
115 if !bytes
.HasPrefix(b
, []byte{'u'}) {
116 return errMissingU8Prefix
118 n
, err
:= strconv
.Atoi(string(b
[1:]))
126 var _ encoding
.TextUnmarshaler
= (*u8marshal
)(nil)
129 um0
, um1 unmarshaler
// target2 of unmarshaling
131 umtrue
= unmarshaler
{true}
132 umslice
= []unmarshaler
{{true}}
133 umslicep
= new([]unmarshaler
)
134 umstruct
= ustruct
{unmarshaler
{true}}
136 um0T
, um1T unmarshalerText
// target2 of unmarshaling
138 umtrueXY
= unmarshalerText
{"x", "y"}
139 umsliceXY
= []unmarshalerText
{{"x", "y"}}
140 umslicepType
= new([]unmarshalerText
)
141 umstructType
= new(ustructText
)
142 umstructXY
= ustructText
{unmarshalerText
{"x", "y"}}
144 ummapType
= map[unmarshalerText
]bool{}
145 ummapXY
= map[unmarshalerText
]bool{unmarshalerText
{"x", "y"}: true}
148 // Test data structures for anonymous fields.
158 *Embed0b
`json:"e,omitempty"` // treated as named
159 Embed0c
`json:"-"` // ignored
161 Embed0p
// has Point with X, Y, used
162 Embed0q
// has Point with Z, used
163 embed
// contains exported field
167 Level1a
int // overridden by Embed0a's Level1a with json tag
168 Level1b
int // used because Embed0a's Level1b is renamed
169 Level1c
int // used because Embed0a's Level1c is ignored
170 Level1d
int // annihilated by Embed0a's Level1d
171 Level1e
int `json:"x"` // annihilated by Embed0a.Level1e
174 type Embed0a
struct {
175 Level1a
int `json:"Level1a,omitempty"`
176 Level1b
int `json:"LEVEL1B,omitempty"`
177 Level1c
int `json:"-"`
178 Level1d
int // annihilated by Embed0's Level1d
179 Level1f
int `json:"x"` // annihilated by Embed0's Level1e
186 type Embed0p
struct {
190 type Embed0q
struct {
199 Loop1
int `json:",omitempty"`
200 Loop2
int `json:",omitempty"`
204 // From reflect test:
205 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
227 // From reflect test:
228 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
248 // Given "hello", the first match should win.
249 First
int `json:"HELLO"`
250 Second
int `json:"Hello"`
259 func sliceAddr(x
[]int) *[]int { return &x
}
260 func mapAddr(x
map[string]int) *map[string]int { return &x
}
262 type byteWithMarshalJSON
byte
264 func (b byteWithMarshalJSON
) MarshalJSON() ([]byte, error
) {
265 return []byte(fmt
.Sprintf(`"Z%.2x"`, byte(b
))), nil
268 func (b
*byteWithMarshalJSON
) UnmarshalJSON(data
[]byte) error
{
269 if len(data
) != 5 || data
[0] != '"' || data
[1] != 'Z' || data
[4] != '"' {
270 return fmt
.Errorf("bad quoted string")
272 i
, err
:= strconv
.ParseInt(string(data
[2:4]), 16, 8)
274 return fmt
.Errorf("bad hex")
276 *b
= byteWithMarshalJSON(i
)
280 type byteWithPtrMarshalJSON
byte
282 func (b
*byteWithPtrMarshalJSON
) MarshalJSON() ([]byte, error
) {
283 return byteWithMarshalJSON(*b
).MarshalJSON()
286 func (b
*byteWithPtrMarshalJSON
) UnmarshalJSON(data
[]byte) error
{
287 return (*byteWithMarshalJSON
)(b
).UnmarshalJSON(data
)
290 type byteWithMarshalText
byte
292 func (b byteWithMarshalText
) MarshalText() ([]byte, error
) {
293 return []byte(fmt
.Sprintf(`Z%.2x`, byte(b
))), nil
296 func (b
*byteWithMarshalText
) UnmarshalText(data
[]byte) error
{
297 if len(data
) != 3 || data
[0] != 'Z' {
298 return fmt
.Errorf("bad quoted string")
300 i
, err
:= strconv
.ParseInt(string(data
[1:3]), 16, 8)
302 return fmt
.Errorf("bad hex")
304 *b
= byteWithMarshalText(i
)
308 type byteWithPtrMarshalText
byte
310 func (b
*byteWithPtrMarshalText
) MarshalText() ([]byte, error
) {
311 return byteWithMarshalText(*b
).MarshalText()
314 func (b
*byteWithPtrMarshalText
) UnmarshalText(data
[]byte) error
{
315 return (*byteWithMarshalText
)(b
).UnmarshalText(data
)
318 type intWithMarshalJSON
int
320 func (b intWithMarshalJSON
) MarshalJSON() ([]byte, error
) {
321 return []byte(fmt
.Sprintf(`"Z%.2x"`, int(b
))), nil
324 func (b
*intWithMarshalJSON
) UnmarshalJSON(data
[]byte) error
{
325 if len(data
) != 5 || data
[0] != '"' || data
[1] != 'Z' || data
[4] != '"' {
326 return fmt
.Errorf("bad quoted string")
328 i
, err
:= strconv
.ParseInt(string(data
[2:4]), 16, 8)
330 return fmt
.Errorf("bad hex")
332 *b
= intWithMarshalJSON(i
)
336 type intWithPtrMarshalJSON
int
338 func (b
*intWithPtrMarshalJSON
) MarshalJSON() ([]byte, error
) {
339 return intWithMarshalJSON(*b
).MarshalJSON()
342 func (b
*intWithPtrMarshalJSON
) UnmarshalJSON(data
[]byte) error
{
343 return (*intWithMarshalJSON
)(b
).UnmarshalJSON(data
)
346 type intWithMarshalText
int
348 func (b intWithMarshalText
) MarshalText() ([]byte, error
) {
349 return []byte(fmt
.Sprintf(`Z%.2x`, int(b
))), nil
352 func (b
*intWithMarshalText
) UnmarshalText(data
[]byte) error
{
353 if len(data
) != 3 || data
[0] != 'Z' {
354 return fmt
.Errorf("bad quoted string")
356 i
, err
:= strconv
.ParseInt(string(data
[1:3]), 16, 8)
358 return fmt
.Errorf("bad hex")
360 *b
= intWithMarshalText(i
)
364 type intWithPtrMarshalText
int
366 func (b
*intWithPtrMarshalText
) MarshalText() ([]byte, error
) {
367 return intWithMarshalText(*b
).MarshalText()
370 func (b
*intWithPtrMarshalText
) UnmarshalText(data
[]byte) error
{
371 return (*intWithMarshalText
)(b
).UnmarshalText(data
)
374 type unmarshalTest
struct {
381 disallowUnknownFields
bool
385 B
bool `json:",string"`
388 var unmarshalTests
= []unmarshalTest
{
390 {in
: `true`, ptr
: new(bool), out
: true},
391 {in
: `1`, ptr
: new(int), out
: 1},
392 {in
: `1.2`, ptr
: new(float64), out
: 1.2},
393 {in
: `-5`, ptr
: new(int16), out
: int16(-5)},
394 {in
: `2`, ptr
: new(Number
), out
: Number("2"), useNumber
: true},
395 {in
: `2`, ptr
: new(Number
), out
: Number("2")},
396 {in
: `2`, ptr
: new(interface{}), out
: float64(2.0)},
397 {in
: `2`, ptr
: new(interface{}), out
: Number("2"), useNumber
: true},
398 {in
: `"a\u1234"`, ptr
: new(string), out
: "a\u1234"},
399 {in
: `"http:\/\/"`, ptr
: new(string), out
: "http://"},
400 {in
: `"g-clef: \uD834\uDD1E"`, ptr
: new(string), out
: "g-clef: \U0001D11E"},
401 {in
: `"invalid: \uD834x\uDD1E"`, ptr
: new(string), out
: "invalid: \uFFFDx\uFFFD"},
402 {in
: "null", ptr
: new(interface{}), out
: nil},
403 {in
: `{"X": [1,2,3], "Y": 4}`, ptr
: new(T
), out
: T
{Y
: 4}, err
: &UnmarshalTypeError
{"array", reflect
.TypeOf(""), 7, "T", "X"}},
404 {in
: `{"x": 1}`, ptr
: new(tx
), out
: tx
{}},
405 {in
: `{"x": 1}`, ptr
: new(tx
), err
: fmt
.Errorf("json: unknown field \"x\""), disallowUnknownFields
: true},
406 {in
: `{"F1":1,"F2":2,"F3":3}`, ptr
: new(V
), out
: V
{F1
: float64(1), F2
: int32(2), F3
: Number("3")}},
407 {in
: `{"F1":1,"F2":2,"F3":3}`, ptr
: new(V
), out
: V
{F1
: Number("1"), F2
: int32(2), F3
: Number("3")}, useNumber
: true},
408 {in
: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr
: new(interface{}), out
: ifaceNumAsFloat64
},
409 {in
: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr
: new(interface{}), out
: ifaceNumAsNumber
, useNumber
: true},
411 // raw values with whitespace
412 {in
: "\n true ", ptr
: new(bool), out
: true},
413 {in
: "\t 1 ", ptr
: new(int), out
: 1},
414 {in
: "\r 1.2 ", ptr
: new(float64), out
: 1.2},
415 {in
: "\t -5 \n", ptr
: new(int16), out
: int16(-5)},
416 {in
: "\t \"a\\u1234\" \n", ptr
: new(string), out
: "a\u1234"},
419 {in
: `{"Y": 1, "Z": 2}`, ptr
: new(T
), out
: T
{Y
: 1}},
420 {in
: `{"Y": 1, "Z": 2}`, ptr
: new(T
), err
: fmt
.Errorf("json: unknown field \"Z\""), disallowUnknownFields
: true},
422 {in
: `{"alpha": "abc", "alphabet": "xyz"}`, ptr
: new(U
), out
: U
{Alphabet
: "abc"}},
423 {in
: `{"alpha": "abc", "alphabet": "xyz"}`, ptr
: new(U
), err
: fmt
.Errorf("json: unknown field \"alphabet\""), disallowUnknownFields
: true},
424 {in
: `{"alpha": "abc"}`, ptr
: new(U
), out
: U
{Alphabet
: "abc"}},
425 {in
: `{"alphabet": "xyz"}`, ptr
: new(U
), out
: U
{}},
426 {in
: `{"alphabet": "xyz"}`, ptr
: new(U
), err
: fmt
.Errorf("json: unknown field \"alphabet\""), disallowUnknownFields
: true},
429 {in
: `{"X": "foo", "Y"}`, err
: &SyntaxError
{"invalid character '}' after object key", 17}},
430 {in
: `[1, 2, 3+]`, err
: &SyntaxError
{"invalid character '+' after array element", 9}},
431 {in
: `{"X":12x}`, err
: &SyntaxError
{"invalid character 'x' after object key:value pair", 8}, useNumber
: true},
434 {in
: "\x01 42", err
: &SyntaxError
{"invalid character '\\x01' looking for beginning of value", 1}},
435 {in
: " 42 \x01", err
: &SyntaxError
{"invalid character '\\x01' after top-level value", 5}},
436 {in
: "\x01 true", err
: &SyntaxError
{"invalid character '\\x01' looking for beginning of value", 1}},
437 {in
: " false \x01", err
: &SyntaxError
{"invalid character '\\x01' after top-level value", 8}},
438 {in
: "\x01 1.2", err
: &SyntaxError
{"invalid character '\\x01' looking for beginning of value", 1}},
439 {in
: " 3.4 \x01", err
: &SyntaxError
{"invalid character '\\x01' after top-level value", 6}},
440 {in
: "\x01 \"string\"", err
: &SyntaxError
{"invalid character '\\x01' looking for beginning of value", 1}},
441 {in
: " \"string\" \x01", err
: &SyntaxError
{"invalid character '\\x01' after top-level value", 11}},
444 {in
: `[1, 2, 3]`, ptr
: new([3]int), out
: [3]int{1, 2, 3}},
445 {in
: `[1, 2, 3]`, ptr
: new([1]int), out
: [1]int{1}},
446 {in
: `[1, 2, 3]`, ptr
: new([5]int), out
: [5]int{1, 2, 3, 0, 0}},
448 // empty array to interface test
449 {in
: `[]`, ptr
: new([]interface{}), out
: []interface{}{}},
450 {in
: `null`, ptr
: new([]interface{}), out
: []interface{}(nil)},
451 {in
: `{"T":[]}`, ptr
: new(map[string]interface{}), out
: map[string]interface{}{"T": []interface{}{}}},
452 {in
: `{"T":null}`, ptr
: new(map[string]interface{}), out
: map[string]interface{}{"T": interface{}(nil)}},
455 {in
: allValueIndent
, ptr
: new(All
), out
: allValue
},
456 {in
: allValueCompact
, ptr
: new(All
), out
: allValue
},
457 {in
: allValueIndent
, ptr
: new(*All
), out
: &allValue
},
458 {in
: allValueCompact
, ptr
: new(*All
), out
: &allValue
},
459 {in
: pallValueIndent
, ptr
: new(All
), out
: pallValue
},
460 {in
: pallValueCompact
, ptr
: new(All
), out
: pallValue
},
461 {in
: pallValueIndent
, ptr
: new(*All
), out
: &pallValue
},
462 {in
: pallValueCompact
, ptr
: new(*All
), out
: &pallValue
},
464 // unmarshal interface test
465 {in
: `{"T":false}`, ptr
: &um0
, out
: umtrue
}, // use "false" so test will fail if custom unmarshaler is not called
466 {in
: `{"T":false}`, ptr
: &ump
, out
: &umtrue
},
467 {in
: `[{"T":false}]`, ptr
: &umslice
, out
: umslice
},
468 {in
: `[{"T":false}]`, ptr
: &umslicep
, out
: &umslice
},
469 {in
: `{"M":{"T":"x:y"}}`, ptr
: &umstruct
, out
: umstruct
},
471 // UnmarshalText interface test
472 {in
: `"x:y"`, ptr
: &um0T
, out
: umtrueXY
},
473 {in
: `"x:y"`, ptr
: &umpType
, out
: &umtrueXY
},
474 {in
: `["x:y"]`, ptr
: &umsliceXY
, out
: umsliceXY
},
475 {in
: `["x:y"]`, ptr
: &umslicepType
, out
: &umsliceXY
},
476 {in
: `{"M":"x:y"}`, ptr
: umstructType
, out
: umstructXY
},
478 // integer-keyed map test
480 in
: `{"-1":"a","0":"b","1":"c"}`,
481 ptr
: new(map[int]string),
482 out
: map[int]string{-1: "a", 0: "b", 1: "c"},
485 in
: `{"0":"a","10":"c","9":"b"}`,
486 ptr
: new(map[u8
]string),
487 out
: map[u8
]string{0: "a", 9: "b", 10: "c"},
490 in
: `{"-9223372036854775808":"min","9223372036854775807":"max"}`,
491 ptr
: new(map[int64]string),
492 out
: map[int64]string{math
.MinInt64
: "min", math
.MaxInt64
: "max"},
495 in
: `{"18446744073709551615":"max"}`,
496 ptr
: new(map[uint64]string),
497 out
: map[uint64]string{math
.MaxUint64
: "max"},
500 in
: `{"0":false,"10":true}`,
501 ptr
: new(map[uintptr]bool),
502 out
: map[uintptr]bool{0: false, 10: true},
505 // Check that MarshalText and UnmarshalText take precedence
506 // over default integer handling in map keys.
509 ptr
: new(map[u8marshal
]int),
510 out
: map[u8marshal
]int{2: 4},
514 ptr
: new(map[u8marshal
]int),
515 err
: errMissingU8Prefix
,
518 // integer-keyed map errors
521 ptr
: new(map[int]string),
522 err
: &UnmarshalTypeError
{Value
: "number abc", Type
: reflect
.TypeOf(0), Offset
: 2},
526 ptr
: new(map[uint8]string),
527 err
: &UnmarshalTypeError
{Value
: "number 256", Type
: reflect
.TypeOf(uint8(0)), Offset
: 2},
531 ptr
: new(map[int8]string),
532 err
: &UnmarshalTypeError
{Value
: "number 128", Type
: reflect
.TypeOf(int8(0)), Offset
: 2},
536 ptr
: new(map[uint8]string),
537 err
: &UnmarshalTypeError
{Value
: "number -1", Type
: reflect
.TypeOf(uint8(0)), Offset
: 2},
540 // Map keys can be encoding.TextUnmarshalers.
541 {in
: `{"x:y":true}`, ptr
: &ummapType
, out
: ummapXY
},
542 // If multiple values for the same key exists, only the most recent value is used.
543 {in
: `{"x:y":false,"x:y":true}`, ptr
: &ummapType
, out
: ummapXY
},
545 // Overwriting of data.
546 // This is different from package xml, but it's what we've always done.
547 // Now documented and tested.
548 {in
: `[2]`, ptr
: sliceAddr([]int{1}), out
: []int{2}},
549 {in
: `{"key": 2}`, ptr
: mapAddr(map[string]int{"old": 0, "key": 1}), out
: map[string]int{"key": 2}},
596 Point
: image
.Point
{X
: 15, Y
: 16},
609 out
: Ambig
{First
: 1},
613 in
: `{"X": 1,"Y":2}`,
615 out
: S5
{S8
: S8
{S9
: S9
{Y
: 2}}},
618 in
: `{"X": 1,"Y":2}`,
620 err
: fmt
.Errorf("json: unknown field \"X\""),
621 disallowUnknownFields
: true,
624 in
: `{"X": 1,"Y":2}`,
626 out
: S10
{S13
: S13
{S8
: S8
{S9
: S9
{Y
: 2}}}},
629 in
: `{"X": 1,"Y":2}`,
631 err
: fmt
.Errorf("json: unknown field \"X\""),
632 disallowUnknownFields
: true,
635 // invalid UTF-8 is coerced to valid UTF-8.
637 in
: "\"hello\xffworld\"",
639 out
: "hello\ufffdworld",
642 in
: "\"hello\xc2\xc2world\"",
644 out
: "hello\ufffd\ufffdworld",
647 in
: "\"hello\xc2\xffworld\"",
649 out
: "hello\ufffd\ufffdworld",
652 in
: "\"hello\\ud800world\"",
654 out
: "hello\ufffdworld",
657 in
: "\"hello\\ud800\\ud800world\"",
659 out
: "hello\ufffd\ufffdworld",
662 in
: "\"hello\\ud800\\ud800world\"",
664 out
: "hello\ufffd\ufffdworld",
667 in
: "\"hello\xed\xa0\x80\xed\xb0\x80world\"",
669 out
: "hello\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdworld",
672 // Used to be issue 8305, but time.Time implements encoding.TextUnmarshaler so this works now.
674 in
: `{"2009-11-10T23:00:00Z": "hello world"}`,
675 ptr
: &map[time
.Time
]string{},
676 out
: map[time
.Time
]string{time
.Date(2009, 11, 10, 23, 0, 0, 0, time
.UTC
): "hello world"},
681 in
: `{"2009-11-10T23:00:00Z": "hello world"}`,
682 ptr
: &map[Point
]string{},
683 err
: &UnmarshalTypeError
{Value
: "object", Type
: reflect
.TypeOf(map[Point
]string{}), Offset
: 1},
686 in
: `{"asdf": "hello world"}`,
687 ptr
: &map[unmarshaler
]string{},
688 err
: &UnmarshalTypeError
{Value
: "object", Type
: reflect
.TypeOf(map[unmarshaler
]string{}), Offset
: 1},
691 // related to issue 13783.
692 // Go 1.7 changed marshaling a slice of typed byte to use the methods on the byte type,
693 // similar to marshaling a slice of typed int.
694 // These tests check that, assuming the byte type also has valid decoding methods,
695 // either the old base64 string encoding or the new per-element encoding can be
696 // successfully unmarshaled. The custom unmarshalers were accessible in earlier
697 // versions of Go, even though the custom marshaler was not.
700 ptr
: new([]byteWithMarshalJSON
),
701 out
: []byteWithMarshalJSON
{1, 2, 3},
704 in
: `["Z01","Z02","Z03"]`,
705 ptr
: new([]byteWithMarshalJSON
),
706 out
: []byteWithMarshalJSON
{1, 2, 3},
711 ptr
: new([]byteWithMarshalText
),
712 out
: []byteWithMarshalText
{1, 2, 3},
715 in
: `["Z01","Z02","Z03"]`,
716 ptr
: new([]byteWithMarshalText
),
717 out
: []byteWithMarshalText
{1, 2, 3},
722 ptr
: new([]byteWithPtrMarshalJSON
),
723 out
: []byteWithPtrMarshalJSON
{1, 2, 3},
726 in
: `["Z01","Z02","Z03"]`,
727 ptr
: new([]byteWithPtrMarshalJSON
),
728 out
: []byteWithPtrMarshalJSON
{1, 2, 3},
733 ptr
: new([]byteWithPtrMarshalText
),
734 out
: []byteWithPtrMarshalText
{1, 2, 3},
737 in
: `["Z01","Z02","Z03"]`,
738 ptr
: new([]byteWithPtrMarshalText
),
739 out
: []byteWithPtrMarshalText
{1, 2, 3},
743 // ints work with the marshaler but not the base64 []byte case
745 in
: `["Z01","Z02","Z03"]`,
746 ptr
: new([]intWithMarshalJSON
),
747 out
: []intWithMarshalJSON
{1, 2, 3},
751 in
: `["Z01","Z02","Z03"]`,
752 ptr
: new([]intWithMarshalText
),
753 out
: []intWithMarshalText
{1, 2, 3},
757 in
: `["Z01","Z02","Z03"]`,
758 ptr
: new([]intWithPtrMarshalJSON
),
759 out
: []intWithPtrMarshalJSON
{1, 2, 3},
763 in
: `["Z01","Z02","Z03"]`,
764 ptr
: new([]intWithPtrMarshalText
),
765 out
: []intWithPtrMarshalText
{1, 2, 3},
769 {in
: `0.000001`, ptr
: new(float64), out
: 0.000001, golden
: true},
770 {in
: `1e-7`, ptr
: new(float64), out
: 1e-7, golden
: true},
771 {in
: `100000000000000000000`, ptr
: new(float64), out
: 100000000000000000000.0, golden
: true},
772 {in
: `1e+21`, ptr
: new(float64), out
: 1e21
, golden
: true},
773 {in
: `-0.000001`, ptr
: new(float64), out
: -0.000001, golden
: true},
774 {in
: `-1e-7`, ptr
: new(float64), out
: -1e-7, golden
: true},
775 {in
: `-100000000000000000000`, ptr
: new(float64), out
: -100000000000000000000.0, golden
: true},
776 {in
: `-1e+21`, ptr
: new(float64), out
: -1e21
, golden
: true},
777 {in
: `999999999999999900000`, ptr
: new(float64), out
: 999999999999999900000.0, golden
: true},
778 {in
: `9007199254740992`, ptr
: new(float64), out
: 9007199254740992.0, golden
: true},
779 {in
: `9007199254740993`, ptr
: new(float64), out
: 9007199254740992.0, golden
: false},
782 in
: `{"V": {"F2": "hello"}}`,
784 err
: &UnmarshalTypeError
{
788 Type
: reflect
.TypeOf(int32(0)),
793 in
: `{"V": {"F4": {}, "F2": "hello"}}`,
795 err
: &UnmarshalTypeError
{
799 Type
: reflect
.TypeOf(int32(0)),
805 // invalid inputs in wrongStringTests below.
806 {in
: `{"B":"true"}`, ptr
: new(B
), out
: B
{true}, golden
: true},
807 {in
: `{"B":"false"}`, ptr
: new(B
), out
: B
{false}, golden
: true},
808 {in
: `{"B": "maybe"}`, ptr
: new(B
), err
: errors
.New(`json: invalid use of ,string struct tag, trying to unmarshal "maybe" into bool`)},
809 {in
: `{"B": "tru"}`, ptr
: new(B
), err
: errors
.New(`json: invalid use of ,string struct tag, trying to unmarshal "tru" into bool`)},
810 {in
: `{"B": "False"}`, ptr
: new(B
), err
: errors
.New(`json: invalid use of ,string struct tag, trying to unmarshal "False" into bool`)},
811 {in
: `{"B": "null"}`, ptr
: new(B
), out
: B
{false}},
812 {in
: `{"B": "nul"}`, ptr
: new(B
), err
: errors
.New(`json: invalid use of ,string struct tag, trying to unmarshal "nul" into bool`)},
814 // additional tests for disallowUnknownFields
839 err
: fmt
.Errorf("json: unknown field \"extra\""),
840 disallowUnknownFields
: true,
866 err
: fmt
.Errorf("json: unknown field \"extra\""),
867 disallowUnknownFields
: true,
871 func TestMarshal(t
*testing
.T
) {
872 b
, err
:= Marshal(allValue
)
874 t
.Fatalf("Marshal allValue: %v", err
)
876 if string(b
) != allValueCompact
{
877 t
.Errorf("Marshal allValueCompact")
878 diff(t
, b
, []byte(allValueCompact
))
882 b
, err
= Marshal(pallValue
)
884 t
.Fatalf("Marshal pallValue: %v", err
)
886 if string(b
) != pallValueCompact
{
887 t
.Errorf("Marshal pallValueCompact")
888 diff(t
, b
, []byte(pallValueCompact
))
893 var badUTF8
= []struct {
896 {"hello\xffworld", `"hello\ufffdworld"`},
898 {"\xff", `"\ufffd"`},
899 {"\xff\xff", `"\ufffd\ufffd"`},
900 {"a\xffb", `"a\ufffdb"`},
901 {"\xe6\x97\xa5\xe6\x9c\xac\xff\xaa\x9e", `"日本\ufffd\ufffd\ufffd"`},
904 func TestMarshalBadUTF8(t
*testing
.T
) {
905 for _
, tt
:= range badUTF8
{
906 b
, err
:= Marshal(tt
.in
)
907 if string(b
) != tt
.out || err
!= nil {
908 t
.Errorf("Marshal(%q) = %#q, %v, want %#q, nil", tt
.in
, b
, err
, tt
.out
)
913 func TestMarshalNumberZeroVal(t
*testing
.T
) {
915 out
, err
:= Marshal(n
)
919 outStr
:= string(out
)
921 t
.Fatalf("Invalid zero val for Number: %q", outStr
)
925 func TestMarshalEmbeds(t
*testing
.T
) {
948 Point
: image
.Point
{X
: 15, Y
: 16},
957 b
, err
:= Marshal(top
)
961 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}"
962 if string(b
) != want
{
963 t
.Errorf("Wrong marshal result.\n got: %q\nwant: %q", b
, want
)
967 func TestUnmarshal(t
*testing
.T
) {
968 for i
, tt
:= range unmarshalTests
{
971 if err
:= checkValid(in
, &scan
); err
!= nil {
972 if !reflect
.DeepEqual(err
, tt
.err
) {
973 t
.Errorf("#%d: checkValid: %#v", i
, err
)
981 // v = new(right-type)
982 v
:= reflect
.New(reflect
.TypeOf(tt
.ptr
).Elem())
983 dec
:= NewDecoder(bytes
.NewReader(in
))
987 if tt
.disallowUnknownFields
{
988 dec
.DisallowUnknownFields()
990 if err
:= dec
.Decode(v
.Interface()); !reflect
.DeepEqual(err
, tt
.err
) {
991 t
.Errorf("#%d: %v, want %v", i
, err
, tt
.err
)
993 } else if err
!= nil {
996 if !reflect
.DeepEqual(v
.Elem().Interface(), tt
.out
) {
997 t
.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i
, v
.Elem().Interface(), tt
.out
)
998 data
, _
:= Marshal(v
.Elem().Interface())
999 println(string(data
))
1000 data
, _
= Marshal(tt
.out
)
1001 println(string(data
))
1005 // Check round trip also decodes correctly.
1007 enc
, err
:= Marshal(v
.Interface())
1009 t
.Errorf("#%d: error re-marshaling: %v", i
, err
)
1012 if tt
.golden
&& !bytes
.Equal(enc
, in
) {
1013 t
.Errorf("#%d: remarshal mismatch:\nhave: %s\nwant: %s", i
, enc
, in
)
1015 vv
:= reflect
.New(reflect
.TypeOf(tt
.ptr
).Elem())
1016 dec
= NewDecoder(bytes
.NewReader(enc
))
1020 if err
:= dec
.Decode(vv
.Interface()); err
!= nil {
1021 t
.Errorf("#%d: error re-unmarshaling %#q: %v", i
, enc
, err
)
1024 if !reflect
.DeepEqual(v
.Elem().Interface(), vv
.Elem().Interface()) {
1025 t
.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i
, v
.Elem().Interface(), vv
.Elem().Interface())
1026 t
.Errorf(" In: %q", strings
.Map(noSpace
, string(in
)))
1027 t
.Errorf("Marshal: %q", strings
.Map(noSpace
, string(enc
)))
1034 func TestUnmarshalMarshal(t
*testing
.T
) {
1037 if err
:= Unmarshal(jsonBig
, &v
); err
!= nil {
1038 t
.Fatalf("Unmarshal: %v", err
)
1040 b
, err
:= Marshal(v
)
1042 t
.Fatalf("Marshal: %v", err
)
1044 if !bytes
.Equal(jsonBig
, b
) {
1045 t
.Errorf("Marshal jsonBig")
1051 var numberTests
= []struct {
1058 {in
: "-1.23e1", intErr
: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f
: -1.23e1
},
1059 {in
: "-12", i
: -12, f
: -12.0},
1060 {in
: "1e1000", intErr
: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr
: "strconv.ParseFloat: parsing \"1e1000\": value out of range"},
1063 // Independent of Decode, basic coverage of the accessors in Number
1064 func TestNumberAccessors(t
*testing
.T
) {
1065 for _
, tt
:= range numberTests
{
1067 if s
:= n
.String(); s
!= tt
.in
{
1068 t
.Errorf("Number(%q).String() is %q", tt
.in
, s
)
1070 if i
, err
:= n
.Int64(); err
== nil && tt
.intErr
== "" && i
!= tt
.i
{
1071 t
.Errorf("Number(%q).Int64() is %d", tt
.in
, i
)
1072 } else if (err
== nil && tt
.intErr
!= "") ||
(err
!= nil && err
.Error() != tt
.intErr
) {
1073 t
.Errorf("Number(%q).Int64() wanted error %q but got: %v", tt
.in
, tt
.intErr
, err
)
1075 if f
, err
:= n
.Float64(); err
== nil && tt
.floatErr
== "" && f
!= tt
.f
{
1076 t
.Errorf("Number(%q).Float64() is %g", tt
.in
, f
)
1077 } else if (err
== nil && tt
.floatErr
!= "") ||
(err
!= nil && err
.Error() != tt
.floatErr
) {
1078 t
.Errorf("Number(%q).Float64() wanted error %q but got: %v", tt
.in
, tt
.floatErr
, err
)
1083 func TestLargeByteSlice(t
*testing
.T
) {
1084 s0
:= make([]byte, 2000)
1088 b
, err
:= Marshal(s0
)
1090 t
.Fatalf("Marshal: %v", err
)
1093 if err
:= Unmarshal(b
, &s1
); err
!= nil {
1094 t
.Fatalf("Unmarshal: %v", err
)
1096 if !bytes
.Equal(s0
, s1
) {
1097 t
.Errorf("Marshal large byte slice")
1106 func TestUnmarshalInterface(t
*testing
.T
) {
1108 var i
interface{} = &xint
1109 if err
:= Unmarshal([]byte(`{"X":1}`), &i
); err
!= nil {
1110 t
.Fatalf("Unmarshal: %v", err
)
1113 t
.Fatalf("Did not write to xint")
1117 func TestUnmarshalPtrPtr(t
*testing
.T
) {
1120 if err
:= Unmarshal([]byte(`{"X":1}`), &pxint
); err
!= nil {
1121 t
.Fatalf("Unmarshal: %v", err
)
1124 t
.Fatalf("Did not write to xint")
1128 func TestEscape(t
*testing
.T
) {
1129 const input
= `"foobar"<html>` + " [\u2028 \u2029]"
1130 const expected
= `"\"foobar\"\u003chtml\u003e [\u2028 \u2029]"`
1131 b
, err
:= Marshal(input
)
1133 t
.Fatalf("Marshal error: %v", err
)
1135 if s
:= string(b
); s
!= expected
{
1136 t
.Errorf("Encoding of [%s]:\n got [%s]\nwant [%s]", input
, s
, expected
)
1140 // WrongString is a struct that's misusing the ,string modifier.
1141 type WrongString
struct {
1142 Message
string `json:"result,string"`
1145 type wrongStringTest
struct {
1149 var wrongStringTests
= []wrongStringTest
{
1150 {`{"result":"x"}`, `json: invalid use of ,string struct tag, trying to unmarshal "x" into string`},
1151 {`{"result":"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "foo" into string`},
1152 {`{"result":"123"}`, `json: invalid use of ,string struct tag, trying to unmarshal "123" into string`},
1153 {`{"result":123}`, `json: invalid use of ,string struct tag, trying to unmarshal unquoted value into string`},
1156 // If people misuse the ,string modifier, the error message should be
1157 // helpful, telling the user that they're doing it wrong.
1158 func TestErrorMessageFromMisusedString(t
*testing
.T
) {
1159 for n
, tt
:= range wrongStringTests
{
1160 r
:= strings
.NewReader(tt
.in
)
1162 err
:= NewDecoder(r
).Decode(&s
)
1163 got
:= fmt
.Sprintf("%v", err
)
1165 t
.Errorf("%d. got err = %q, want %q", n
, got
, tt
.err
)
1170 func noSpace(c rune
) rune
{
1171 if isSpace(byte(c
)) { //only used for ascii
1193 Foo
string `json:"bar"`
1194 Foo2
string `json:"bar2,dummyopt"`
1196 IntStr
int64 `json:",string"`
1197 UintptrStr
uintptr `json:",string"`
1217 Map
map[string]Small
1218 MapP
map[string]*Small
1219 PMap
*map[string]Small
1220 PMapP
*map[string]*Small
1222 EmptyMap
map[string]Small
1223 NilMap
map[string]Small
1233 StringSlice
[]string
1240 Interface
interface{}
1241 PInterface
*interface{}
1270 Map
: map[string]Small
{
1271 "17": {Tag
: "tag17"},
1272 "18": {Tag
: "tag18"},
1274 MapP
: map[string]*Small
{
1275 "19": {Tag
: "tag19"},
1278 EmptyMap
: map[string]Small
{},
1279 Slice
: []Small
{{Tag
: "tag20"}, {Tag
: "tag21"}},
1280 SliceP
: []*Small
{{Tag
: "tag22"}, nil, {Tag
: "tag23"}},
1281 EmptySlice
: []Small
{},
1282 StringSlice
: []string{"str24", "str25", "str26"},
1283 ByteSlice
: []byte{27, 28, 29},
1284 Small
: Small
{Tag
: "tag30"},
1285 PSmall
: &Small
{Tag
: "tag31"},
1289 var pallValue
= All
{
1290 PBool
: &allValue
.Bool
,
1291 PInt
: &allValue
.Int
,
1292 PInt8
: &allValue
.Int8
,
1293 PInt16
: &allValue
.Int16
,
1294 PInt32
: &allValue
.Int32
,
1295 PInt64
: &allValue
.Int64
,
1296 PUint
: &allValue
.Uint
,
1297 PUint8
: &allValue
.Uint8
,
1298 PUint16
: &allValue
.Uint16
,
1299 PUint32
: &allValue
.Uint32
,
1300 PUint64
: &allValue
.Uint64
,
1301 PUintptr
: &allValue
.Uintptr
,
1302 PFloat32
: &allValue
.Float32
,
1303 PFloat64
: &allValue
.Float64
,
1304 PString
: &allValue
.String
,
1305 PMap
: &allValue
.Map
,
1306 PMapP
: &allValue
.MapP
,
1307 PSlice
: &allValue
.Slice
,
1308 PSliceP
: &allValue
.SliceP
,
1309 PPSmall
: &allValue
.PSmall
,
1310 PInterface
: &allValue
.Interface
,
1313 var allValueIndent
= `{
1392 "ByteSlice": "Gxwd",
1404 var allValueCompact
= strings
.Map(noSpace
, allValueIndent
)
1406 var pallValueIndent
= `{
1480 "StringSlice": null,
1493 var pallValueCompact
= strings
.Map(noSpace
, pallValueIndent
)
1495 func TestRefUnmarshal(t
*testing
.T
) {
1497 // Ref is defined in encode_test.go.
1513 if err
:= Unmarshal([]byte(`{"R0":"ref","R1":"ref","R2":"ref","R3":"ref"}`), &got
); err
!= nil {
1514 t
.Fatalf("Unmarshal: %v", err
)
1516 if !reflect
.DeepEqual(got
, want
) {
1517 t
.Errorf("got %+v, want %+v", got
, want
)
1521 // Test that the empty string doesn't panic decoding when ,string is specified
1523 func TestEmptyString(t
*testing
.T
) {
1525 Number1
int `json:",string"`
1526 Number2
int `json:",string"`
1528 data
:= `{"Number1":"1", "Number2":""}`
1529 dec
:= NewDecoder(strings
.NewReader(data
))
1531 err
:= dec
.Decode(&t2
)
1533 t
.Fatal("Decode: did not return error")
1535 if t2
.Number1
!= 1 {
1536 t
.Fatal("Decode: did not set Number1")
1540 // Test that a null for ,string is not replaced with the previous quoted string (issue 7046).
1541 // It should also not be an error (issue 2540, issue 8587).
1542 func TestNullString(t
*testing
.T
) {
1544 A
int `json:",string"`
1545 B
int `json:",string"`
1546 C
*int `json:",string"`
1548 data
:= []byte(`{"A": "1", "B": null, "C": null}`)
1553 err
:= Unmarshal(data
, &s
)
1555 t
.Fatalf("Unmarshal: %v", err
)
1557 if s
.B
!= 1 || s
.C
!= nil {
1558 t
.Fatalf("after Unmarshal, s.B=%d, s.C=%p, want 1, nil", s
.B
, s
.C
)
1562 func intp(x
int) *int {
1568 func intpp(x
*int) **int {
1574 var interfaceSetTests
= []struct {
1579 {"foo", `"bar"`, "bar"},
1581 {"foo", `true`, true},
1582 {"foo", `null`, nil},
1585 {new(int), `null`, nil},
1586 {(*int)(nil), `null`, nil},
1587 {new(*int), `null`, new(*int)},
1588 {(**int)(nil), `null`, nil},
1589 {intp(1), `null`, nil},
1590 {intpp(nil), `null`, intpp(nil)},
1591 {intpp(intp(1)), `null`, intpp(nil)},
1594 func TestInterfaceSet(t
*testing
.T
) {
1595 for _
, tt
:= range interfaceSetTests
{
1596 b
:= struct{ X
interface{} }{tt
.pre
}
1597 blob
:= `{"X":` + tt
.json
+ `}`
1598 if err
:= Unmarshal([]byte(blob
), &b
); err
!= nil {
1599 t
.Errorf("Unmarshal %#q: %v", blob
, err
)
1602 if !reflect
.DeepEqual(b
.X
, tt
.post
) {
1603 t
.Errorf("Unmarshal %#q into %#v: X=%#v, want %#v", blob
, tt
.pre
, b
.X
, tt
.post
)
1608 type NullTest
struct {
1624 Map
map[string]string
1626 Interface
interface{}
1631 PText
*MustNotUnmarshalText
1632 PBuffer
*bytes
.Buffer
// has methods, just not relevant ones
1638 Text MustNotUnmarshalText
1643 type NullTestStrings
struct {
1644 Bool
bool `json:",string"`
1645 Int
int `json:",string"`
1646 Int8
int8 `json:",string"`
1647 Int16
int16 `json:",string"`
1648 Int32
int32 `json:",string"`
1649 Int64
int64 `json:",string"`
1650 Uint
uint `json:",string"`
1651 Uint8
uint8 `json:",string"`
1652 Uint16
uint16 `json:",string"`
1653 Uint32
uint32 `json:",string"`
1654 Uint64
uint64 `json:",string"`
1655 Float32
float32 `json:",string"`
1656 Float64
float64 `json:",string"`
1657 String
string `json:",string"`
1658 PBool
*bool `json:",string"`
1659 Map
map[string]string `json:",string"`
1660 Slice
[]string `json:",string"`
1661 Interface
interface{} `json:",string"`
1663 PRaw
*RawMessage
`json:",string"`
1664 PTime
*time
.Time
`json:",string"`
1665 PBigInt
*big
.Int
`json:",string"`
1666 PText
*MustNotUnmarshalText
`json:",string"`
1667 PBuffer
*bytes
.Buffer
`json:",string"`
1668 PStruct
*struct{} `json:",string"`
1670 Raw RawMessage
`json:",string"`
1671 Time time
.Time
`json:",string"`
1672 BigInt big
.Int
`json:",string"`
1673 Text MustNotUnmarshalText
`json:",string"`
1674 Buffer bytes
.Buffer
`json:",string"`
1675 Struct
struct{} `json:",string"`
1678 // JSON null values should be ignored for primitives and string values instead of resulting in an error.
1680 func TestUnmarshalNulls(t
*testing
.T
) {
1682 // The JSON null value unmarshals into an interface, map, pointer, or slice
1683 // by setting that Go value to nil. Because null is often used in JSON to mean
1684 // ``not present,'' unmarshaling a JSON null into any other Go type has no effect
1685 // on the value and produces no error.
1687 jsonData
:= []byte(`{
1735 Map
: map[string]string{},
1737 Interface
: new(MustNotUnmarshalJSON
),
1738 PRaw
: new(RawMessage
),
1739 PTime
: new(time
.Time
),
1740 PBigInt
: new(big
.Int
),
1741 PText
: new(MustNotUnmarshalText
),
1742 PStruct
: new(struct{}),
1743 PBuffer
: new(bytes
.Buffer
),
1744 Raw
: RawMessage("123"),
1745 Time
: time
.Unix(123456789, 0),
1746 BigInt
: *big
.NewInt(123),
1749 before
:= nulls
.Time
.String()
1751 err
:= Unmarshal(jsonData
, &nulls
)
1753 t
.Errorf("Unmarshal of null values failed: %v", err
)
1755 if !nulls
.Bool || nulls
.Int
!= 2 || nulls
.Int8
!= 3 || nulls
.Int16
!= 4 || nulls
.Int32
!= 5 || nulls
.Int64
!= 6 ||
1756 nulls
.Uint
!= 7 || nulls
.Uint8
!= 8 || nulls
.Uint16
!= 9 || nulls
.Uint32
!= 10 || nulls
.Uint64
!= 11 ||
1757 nulls
.Float32
!= 12.1 || nulls
.Float64
!= 13.1 || nulls
.String
!= "14" {
1758 t
.Errorf("Unmarshal of null values affected primitives")
1761 if nulls
.PBool
!= nil {
1762 t
.Errorf("Unmarshal of null did not clear nulls.PBool")
1764 if nulls
.Map
!= nil {
1765 t
.Errorf("Unmarshal of null did not clear nulls.Map")
1767 if nulls
.Slice
!= nil {
1768 t
.Errorf("Unmarshal of null did not clear nulls.Slice")
1770 if nulls
.Interface
!= nil {
1771 t
.Errorf("Unmarshal of null did not clear nulls.Interface")
1773 if nulls
.PRaw
!= nil {
1774 t
.Errorf("Unmarshal of null did not clear nulls.PRaw")
1776 if nulls
.PTime
!= nil {
1777 t
.Errorf("Unmarshal of null did not clear nulls.PTime")
1779 if nulls
.PBigInt
!= nil {
1780 t
.Errorf("Unmarshal of null did not clear nulls.PBigInt")
1782 if nulls
.PText
!= nil {
1783 t
.Errorf("Unmarshal of null did not clear nulls.PText")
1785 if nulls
.PBuffer
!= nil {
1786 t
.Errorf("Unmarshal of null did not clear nulls.PBuffer")
1788 if nulls
.PStruct
!= nil {
1789 t
.Errorf("Unmarshal of null did not clear nulls.PStruct")
1792 if string(nulls
.Raw
) != "null" {
1793 t
.Errorf("Unmarshal of RawMessage null did not record null: %v", string(nulls
.Raw
))
1795 if nulls
.Time
.String() != before
{
1796 t
.Errorf("Unmarshal of time.Time null set time to %v", nulls
.Time
.String())
1798 if nulls
.BigInt
.String() != "123" {
1799 t
.Errorf("Unmarshal of big.Int null set int to %v", nulls
.BigInt
.String())
1803 type MustNotUnmarshalJSON
struct{}
1805 func (x MustNotUnmarshalJSON
) UnmarshalJSON(data
[]byte) error
{
1806 return errors
.New("MustNotUnmarshalJSON was used")
1809 type MustNotUnmarshalText
struct{}
1811 func (x MustNotUnmarshalText
) UnmarshalText(text
[]byte) error
{
1812 return errors
.New("MustNotUnmarshalText was used")
1815 func TestStringKind(t
*testing
.T
) {
1816 type stringKind
string
1818 var m1
, m2
map[stringKind
]int
1819 m1
= map[stringKind
]int{
1823 data
, err
:= Marshal(m1
)
1825 t
.Errorf("Unexpected error marshaling: %v", err
)
1828 err
= Unmarshal(data
, &m2
)
1830 t
.Errorf("Unexpected error unmarshaling: %v", err
)
1833 if !reflect
.DeepEqual(m1
, m2
) {
1834 t
.Error("Items should be equal after encoding and then decoding")
1838 // Custom types with []byte as underlying type could not be marshaled
1839 // and then unmarshaled.
1841 func TestByteKind(t
*testing
.T
) {
1842 type byteKind
[]byte
1844 a
:= byteKind("hello")
1846 data
, err
:= Marshal(a
)
1851 err
= Unmarshal(data
, &b
)
1855 if !reflect
.DeepEqual(a
, b
) {
1856 t
.Errorf("expected %v == %v", a
, b
)
1860 // The fix for issue 8962 introduced a regression.
1862 func TestSliceOfCustomByte(t
*testing
.T
) {
1865 a
:= []Uint8("hello")
1867 data
, err
:= Marshal(a
)
1872 err
= Unmarshal(data
, &b
)
1876 if !reflect
.DeepEqual(a
, b
) {
1877 t
.Fatalf("expected %v == %v", a
, b
)
1881 var decodeTypeErrorTests
= []struct {
1885 {new(string), `{"user": "name"}`}, // issue 4628.
1886 {new(error
), `{}`}, // issue 4222
1889 {new(error
), `123`},
1890 {new(error
), `true`},
1893 func TestUnmarshalTypeError(t
*testing
.T
) {
1894 for _
, item
:= range decodeTypeErrorTests
{
1895 err
:= Unmarshal([]byte(item
.src
), item
.dest
)
1896 if _
, ok
:= err
.(*UnmarshalTypeError
); !ok
{
1897 t
.Errorf("expected type error for Unmarshal(%q, type %T): got %T",
1898 item
.src
, item
.dest
, err
)
1903 var unmarshalSyntaxTests
= []string{
1914 func TestUnmarshalSyntax(t
*testing
.T
) {
1916 for _
, src
:= range unmarshalSyntaxTests
{
1917 err
:= Unmarshal([]byte(src
), &x
)
1918 if _
, ok
:= err
.(*SyntaxError
); !ok
{
1919 t
.Errorf("expected syntax error for Unmarshal(%q): got %T", src
, err
)
1924 // Test handling of unexported fields that should be ignored.
1926 type unexportedFields
struct {
1928 m
map[string]interface{} `json:"-"`
1929 m2
map[string]interface{} `json:"abcd"`
1932 func TestUnmarshalUnexported(t
*testing
.T
) {
1933 input
:= `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}}`
1934 want
:= &unexportedFields
{Name
: "Bob"}
1936 out
:= &unexportedFields
{}
1937 err
:= Unmarshal([]byte(input
), out
)
1939 t
.Errorf("got error %v, expected nil", err
)
1941 if !reflect
.DeepEqual(out
, want
) {
1942 t
.Errorf("got %q, want %q", out
, want
)
1946 // Time3339 is a time.Time which encodes to and from JSON
1947 // as an RFC 3339 time in UTC.
1948 type Time3339 time
.Time
1950 func (t
*Time3339
) UnmarshalJSON(b
[]byte) error
{
1951 if len(b
) < 2 || b
[0] != '"' || b
[len(b
)-1] != '"' {
1952 return fmt
.Errorf("types: failed to unmarshal non-string value %q as an RFC 3339 time", b
)
1954 tm
, err
:= time
.Parse(time
.RFC3339
, string(b
[1:len(b
)-1]))
1962 func TestUnmarshalJSONLiteralError(t
*testing
.T
) {
1964 err
:= Unmarshal([]byte(`"0000-00-00T00:00:00Z"`), &t3
)
1966 t
.Fatalf("expected error; got time %v", time
.Time(t3
))
1968 if !strings
.Contains(err
.Error(), "range") {
1969 t
.Errorf("got err = %v; want out of range error", err
)
1973 // Test that extra object elements in an array do not result in a
1974 // "data changing underfoot" error.
1976 func TestSkipArrayObjects(t
*testing
.T
) {
1978 var dest
[0]interface{}
1980 err
:= Unmarshal([]byte(json
), &dest
)
1982 t
.Errorf("got error %q, want nil", err
)
1986 // Test semantics of pre-filled struct fields and pre-filled map fields.
1988 func TestPrefilled(t
*testing
.T
) {
1989 ptrToMap
:= func(m
map[string]interface{}) *map[string]interface{} { return &m
}
1991 // Values here change, cannot reuse table across runs.
1992 var prefillTests
= []struct {
1998 in
: `{"X": 1, "Y": 2}`,
1999 ptr
: &XYZ
{X
: float32(3), Y
: int16(4), Z
: 1.5},
2000 out
: &XYZ
{X
: float64(1), Y
: float64(2), Z
: 1.5},
2003 in
: `{"X": 1, "Y": 2}`,
2004 ptr
: ptrToMap(map[string]interface{}{"X": float32(3), "Y": int16(4), "Z": 1.5}),
2005 out
: ptrToMap(map[string]interface{}{"X": float64(1), "Y": float64(2), "Z": 1.5}),
2009 for _
, tt
:= range prefillTests
{
2010 ptrstr
:= fmt
.Sprintf("%v", tt
.ptr
)
2011 err
:= Unmarshal([]byte(tt
.in
), tt
.ptr
) // tt.ptr edited here
2013 t
.Errorf("Unmarshal: %v", err
)
2015 if !reflect
.DeepEqual(tt
.ptr
, tt
.out
) {
2016 t
.Errorf("Unmarshal(%#q, %s): have %v, want %v", tt
.in
, ptrstr
, tt
.ptr
, tt
.out
)
2021 var invalidUnmarshalTests
= []struct {
2025 {nil, "json: Unmarshal(nil)"},
2026 {struct{}{}, "json: Unmarshal(non-pointer struct {})"},
2027 {(*int)(nil), "json: Unmarshal(nil *int)"},
2030 func TestInvalidUnmarshal(t
*testing
.T
) {
2031 buf
:= []byte(`{"a":"1"}`)
2032 for _
, tt
:= range invalidUnmarshalTests
{
2033 err
:= Unmarshal(buf
, tt
.v
)
2035 t
.Errorf("Unmarshal expecting error, got nil")
2038 if got
:= err
.Error(); got
!= tt
.want
{
2039 t
.Errorf("Unmarshal = %q; want %q", got
, tt
.want
)
2044 var invalidUnmarshalTextTests
= []struct {
2048 {nil, "json: Unmarshal(nil)"},
2049 {struct{}{}, "json: Unmarshal(non-pointer struct {})"},
2050 {(*int)(nil), "json: Unmarshal(nil *int)"},
2051 {new(net
.IP
), "json: cannot unmarshal number into Go value of type *net.IP"},
2054 func TestInvalidUnmarshalText(t
*testing
.T
) {
2055 buf
:= []byte(`123`)
2056 for _
, tt
:= range invalidUnmarshalTextTests
{
2057 err
:= Unmarshal(buf
, tt
.v
)
2059 t
.Errorf("Unmarshal expecting error, got nil")
2062 if got
:= err
.Error(); got
!= tt
.want
{
2063 t
.Errorf("Unmarshal = %q; want %q", got
, tt
.want
)
2068 // Test that string option is ignored for invalid types.
2070 func TestInvalidStringOption(t
*testing
.T
) {
2073 T time
.Time
`json:",string"`
2074 M
map[string]string `json:",string"`
2075 S
[]string `json:",string"`
2076 A
[1]string `json:",string"`
2077 I
interface{} `json:",string"`
2078 P
*int `json:",string"`
2079 }{M
: make(map[string]string), S
: make([]string, 0), I
: num
, P
: &num
}
2081 data
, err
:= Marshal(item
)
2083 t
.Fatalf("Marshal: %v", err
)
2086 err
= Unmarshal(data
, &item
)
2088 t
.Fatalf("Unmarshal: %v", err
)
2092 // Test unmarshal behavior with regards to embedded unexported structs.
2094 // (Issue 21357) If the embedded struct is a pointer and is unallocated,
2095 // this returns an error because unmarshal cannot set the field.
2097 // (Issue 24152) If the embedded struct is given an explicit name,
2098 // ensure that the normal unmarshal logic does not panic in reflect.
2099 func TestUnmarshalEmbeddedUnexported(t
*testing
.T
) {
2101 embed1
struct{ Q
int }
2102 embed2
struct{ Q
int }
2104 Q
int64 `json:",string"`
2127 embed1
`json:"embed1"`
2130 embed1
`json:"embed1"`
2134 embed1
`json:"embed1"`
2135 embed2
`json:"embed2"`
2146 // Error since we cannot set S1.embed1, but still able to set S1.R.
2147 in
: `{"R":2,"Q":1}`,
2150 err
: fmt
.Errorf("json: cannot set embedded pointer to unexported struct: json.embed1"),
2152 // The top level Q field takes precedence.
2157 // No issue with non-pointer variant.
2158 in
: `{"R":2,"Q":1}`,
2160 out
: &S3
{embed1
: embed1
{Q
: 1}, R
: 2},
2162 // No error since both embedded structs have field R, which annihilate each other.
2163 // Thus, no attempt is made at setting S4.embed1.
2168 // Error since we cannot set S5.embed1, but still able to set S5.R.
2169 in
: `{"R":2,"Q":1}`,
2172 err
: fmt
.Errorf("json: cannot set embedded pointer to unexported struct: json.embed3"),
2174 // Issue 24152, ensure decodeState.indirect does not panic.
2175 in
: `{"embed1": {"Q": 1}}`,
2177 out
: &S6
{embed1
{1}},
2179 // Issue 24153, check that we can still set forwarded fields even in
2180 // the presence of a name conflict.
2182 // This relies on obscure behavior of reflect where it is possible
2183 // to set a forwarded exported field on an unexported embedded struct
2184 // even though there is a name conflict, even when it would have been
2185 // impossible to do so according to Go visibility rules.
2186 // Go forbids this because it is ambiguous whether S7.Q refers to
2187 // S7.embed1.Q or S7.embed2.Q. Since embed1 and embed2 are unexported,
2188 // it should be impossible for an external package to set either Q.
2190 // It is probably okay for a future reflect change to break this.
2191 in
: `{"embed1": {"Q": 1}, "Q": 2}`,
2193 out
: &S7
{embed1
{1}, embed2
{2}},
2195 // Issue 24153, similar to the S7 case.
2196 in
: `{"embed1": {"Q": 1}, "embed2": {"Q": 2}, "Q": 3}`,
2198 out
: &S8
{embed1
{1}, embed2
{2}, 3},
2201 for i
, tt
:= range tests
{
2202 err
:= Unmarshal([]byte(tt
.in
), tt
.ptr
)
2203 if !reflect
.DeepEqual(err
, tt
.err
) {
2204 t
.Errorf("#%d: %v, want %v", i
, err
, tt
.err
)
2206 if !reflect
.DeepEqual(tt
.ptr
, tt
.out
) {
2207 t
.Errorf("#%d: mismatch\ngot: %#+v\nwant: %#+v", i
, tt
.ptr
, tt
.out
)