forked from mirror/go-json
Support decoding for bool type
This commit is contained in:
parent
0c42c47179
commit
416d1cf552
22
decode.go
22
decode.go
|
@ -1,6 +1,7 @@
|
|||
package json
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
|
@ -197,6 +198,8 @@ func (d *Decoder) compile(v reflect.Value) (DecodeOp, error) {
|
|||
return d.compileUint64()
|
||||
case reflect.String:
|
||||
return d.compileString()
|
||||
case reflect.Bool:
|
||||
return d.compileBool()
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -356,6 +359,25 @@ func (d *Decoder) compileString() (DecodeOp, error) {
|
|||
}, nil
|
||||
}
|
||||
|
||||
var (
|
||||
trueBytes = []byte("true")
|
||||
falseBytes = []byte("false")
|
||||
)
|
||||
|
||||
func (d *Decoder) compileBool() (DecodeOp, error) {
|
||||
return func(p uintptr, src []byte, _ []byte) error {
|
||||
if bytes.Equal(src, trueBytes) {
|
||||
*(*bool)(unsafe.Pointer(p)) = true
|
||||
return nil
|
||||
}
|
||||
if bytes.Equal(src, falseBytes) {
|
||||
*(*bool)(unsafe.Pointer(p)) = false
|
||||
return nil
|
||||
}
|
||||
return errors.New("unexpected error bool")
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *Decoder) getTag(field reflect.StructField) string {
|
||||
return field.Tag.Get("json")
|
||||
}
|
||||
|
|
|
@ -11,9 +11,11 @@ func Test_Decoder(t *testing.T) {
|
|||
var v struct {
|
||||
A int `json:"abcd"`
|
||||
B string `json:"str"`
|
||||
C bool
|
||||
}
|
||||
assertErr(t, json.Unmarshal([]byte(`{ "abcd" : 123 , "str" : "hello" }`), &v))
|
||||
assertErr(t, json.Unmarshal([]byte(`{ "abcd" : 123 , "str" : "hello", "c": true }`), &v))
|
||||
assertEq(t, "struct.A", 123, v.A)
|
||||
assertEq(t, "struct.B", "hello", v.B)
|
||||
assertEq(t, "struct.C", true, v.C)
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue