mirror of
https://github.com/json-iterator/go.git
synced 2025-01-05 12:50:34 +02:00
#68 string to int
This commit is contained in:
parent
818ae1331a
commit
306b2896cf
@ -8,6 +8,7 @@ import (
|
||||
|
||||
func RegisterFuzzyDecoders() {
|
||||
jsoniter.RegisterTypeDecoder("string", &FuzzyStringDecoder{})
|
||||
jsoniter.RegisterTypeDecoder("int", &FuzzyIntDecoder{})
|
||||
}
|
||||
|
||||
type FuzzyStringDecoder struct {
|
||||
@ -26,3 +27,21 @@ func (decoder *FuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Ite
|
||||
iter.ReportError("FuzzyStringDecoder", "not number or string")
|
||||
}
|
||||
}
|
||||
|
||||
type FuzzyIntDecoder struct {
|
||||
}
|
||||
|
||||
func (decoder *FuzzyIntDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||
valueType := iter.WhatIsNext()
|
||||
switch valueType {
|
||||
case jsoniter.Number:
|
||||
// use current iterator
|
||||
case jsoniter.String:
|
||||
str := iter.ReadString()
|
||||
iter = iter.Config().BorrowIterator([]byte(str))
|
||||
defer iter.Config().ReturnIterator(iter)
|
||||
default:
|
||||
iter.ReportError("FuzzyIntDecoder", "not number or string")
|
||||
}
|
||||
*((*int)(ptr)) = iter.ReadInt()
|
||||
}
|
||||
|
@ -10,6 +10,13 @@ func init() {
|
||||
RegisterFuzzyDecoders()
|
||||
}
|
||||
|
||||
func Test_string_to_string(t *testing.T) {
|
||||
should := require.New(t)
|
||||
var val string
|
||||
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||
should.Equal("100", val)
|
||||
}
|
||||
|
||||
func Test_int_to_string(t *testing.T) {
|
||||
should := require.New(t)
|
||||
var val string
|
||||
@ -23,3 +30,17 @@ func Test_float_to_string(t *testing.T) {
|
||||
should.Nil(jsoniter.UnmarshalFromString(`12.0`, &val))
|
||||
should.Equal("12.0", val)
|
||||
}
|
||||
|
||||
func Test_string_to_int(t *testing.T) {
|
||||
should := require.New(t)
|
||||
var val int
|
||||
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||
should.Equal(100, val)
|
||||
}
|
||||
|
||||
func Test_int_to_int(t *testing.T) {
|
||||
should := require.New(t)
|
||||
var val int
|
||||
should.Nil(jsoniter.UnmarshalFromString(`100`, &val))
|
||||
should.Equal(100, val)
|
||||
}
|
||||
|
@ -113,6 +113,10 @@ func ParseString(cfg *frozenConfig, input string) *Iterator {
|
||||
return ParseBytes(cfg, []byte(input))
|
||||
}
|
||||
|
||||
func (iter *Iterator) Config() *frozenConfig {
|
||||
return iter.cfg
|
||||
}
|
||||
|
||||
// Reset can reset an Iterator instance for another json buffer in io.Reader
|
||||
func (iter *Iterator) Reset(reader io.Reader) *Iterator {
|
||||
iter.reader = reader
|
||||
|
Loading…
Reference in New Issue
Block a user