1
0
mirror of https://github.com/json-iterator/go.git synced 2025-02-01 19:14:29 +02:00

add Any.ToVal

This commit is contained in:
Tao Wen 2017-06-19 15:40:00 +08:00
parent 31afe6450e
commit 514db10f97
5 changed files with 28 additions and 0 deletions

View File

@ -19,10 +19,14 @@ type Any interface {
ToFloat32() float32
ToFloat64() float64
ToString() string
ToVal(val interface{})
Get(path ...interface{}) Any
// TODO: add Set
Size() int
Keys() []string
// TODO: remove me
GetArray() []Any
// TODO: remove me
GetObject() map[string]Any
GetInterface() interface{}
WriteTo(stream *Stream)
@ -50,6 +54,10 @@ func (any *baseAny) GetObject() map[string]Any {
return map[string]Any{}
}
func (any *baseAny) ToVal(obj interface{}) {
panic("not implemented")
}
func WrapInt32(val int32) Any {
return &int32Any{baseAny{}, val}
}

View File

@ -94,6 +94,12 @@ func (any *arrayLazyAny) ToString() string {
return *(*string)(unsafe.Pointer(&any.buf))
}
func (any *arrayLazyAny) ToVal(val interface{}) {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadVal(val)
}
func (any *arrayLazyAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any

View File

@ -94,6 +94,12 @@ func (any *objectLazyAny) ToString() string {
return *(*string)(unsafe.Pointer(&any.buf))
}
func (any *objectLazyAny) ToVal(obj interface{}) {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadVal(obj)
}
func (any *objectLazyAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any

View File

@ -41,6 +41,9 @@ func Test_read_two_element_array_as_any(t *testing.T) {
stream := NewStream(ConfigDefault, nil, 32)
any.WriteTo(stream)
should.Equal("[1,2]", string(stream.Buffer()))
arr := []int{}
any.ToVal(&arr)
should.Equal([]int{1, 2}, arr)
}
func Test_wrap_array(t *testing.T) {

View File

@ -22,6 +22,11 @@ func Test_read_object_as_any(t *testing.T) {
should.Equal(Object, any.ValueType())
should.Nil(any.LastError())
should.Equal("b", any.GetObject()["a"].ToString())
obj := struct {
A string
}{}
any.ToVal(&obj)
should.Equal("b", obj.A)
}
func Test_object_lazy_any_get(t *testing.T) {