Golang 超快JSON 解析,基于 github.com/json-iterator/go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"fmt"
"reflect"
"unsafe"
"github.com/json-iterator/go"
)
type StructOfTag struct {
field1 string `json:"field-1"`
field2 string `json:"-"`
field3 int `json:",string"`
}
func str2byte(s string) []byte {
x := (*[2]uintptr)(unsafe.Pointer(&s))
h := [3]uintptr{x[0], x[1], x[1]}
return *(*[]byte)(unsafe.Pointer(&h))
}
func byte2str(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func b2s(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// s2b converts string to a byte slice without memory allocation.
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func s2b(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{
Data: sh.Data,
Len: sh.Len,
Cap: sh.Len,
}
return *(*[]byte)(unsafe.Pointer(&bh))
}
func main() {
struct_ := StructOfTag{}
//jsoniter.Unmarshal([]byte(`{"field-1": "hello", "field2": "", "field3": "100"}`), &struct_)
jsoniter.Unmarshal(s2b(`{"field-1": "hello", "field2": "", "field3": "100"}`), &struct_)
fmt.Println(struct_)
}
输出:
1
{hello 100}
更新
这个库已经能完全兼容标准库 encoding/json
,在使用中只需重新定义 json
,线程安全!
1
2
3
4
5
6
import jsoniter "github.com/json-iterator/go"
var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Marshal(&data)
json.Unmarshal(input, &data)
本文网址: https://golangnote.com/topic/143.html 转摘请注明来源