1
0
mirror of https://github.com/json-iterator/go.git synced 2025-04-23 11:37:32 +02:00
json-iterator/feature_adapter.go

47 lines
908 B
Go
Raw Normal View History

2016-12-04 22:50:53 +08:00
package jsoniter
2017-01-06 20:17:47 +08:00
import (
"io"
"unsafe"
2017-01-07 12:28:16 +08:00
"bytes"
2017-01-06 20:17:47 +08:00
)
2016-12-05 13:20:27 +08:00
// Unmarshal adapts to json/encoding APIs
2016-12-04 22:50:53 +08:00
func Unmarshal(data []byte, v interface{}) error {
iter := ParseBytes(data)
2017-01-09 17:47:21 +08:00
iter.ReadVal(v)
2016-12-05 13:20:27 +08:00
if iter.Error == io.EOF {
return nil
}
2016-12-04 22:50:53 +08:00
return iter.Error
}
2017-01-06 20:17:47 +08:00
2017-01-07 12:28:16 +08:00
func UnmarshalFromString(str string, v interface{}) error {
// safe to do the unsafe cast here, as str is always referenced in this scope
2017-01-06 20:17:47 +08:00
data := *(*[]byte)(unsafe.Pointer(&str))
iter := ParseBytes(data)
2017-01-09 17:47:21 +08:00
iter.ReadVal(v)
2017-01-06 20:17:47 +08:00
if iter.Error == io.EOF {
return nil
}
return iter.Error
}
2017-01-07 12:28:16 +08:00
func Marshal(v interface{}) ([]byte, error) {
buf := &bytes.Buffer{}
stream := NewStream(buf, 4096)
stream.WriteVal(v)
2017-01-09 19:19:48 +08:00
stream.Flush()
2017-01-07 12:28:16 +08:00
if stream.Error != nil {
return nil, stream.Error
}
return buf.Bytes(), nil
}
func MarshalToString(v interface{}) (string, error) {
buf, err := Marshal(v)
if err != nil {
return "", err
}
return string(buf), nil
}