jsoniter ( json-iterator )是一款快且灵活的 JSON 解析器,同时提供 Java 和 Go 两个版本Jsoniter 是最快的 JSON 解析.
器。它最多能比普通的解析器快 10 倍之多,即使在数据绑定的用法下也有同样的性能优势。
Golang中的跑分图(来自网上):
有时候,例如一个JSON对象很大,字段很多,完全没有必要为了访问几个字段而创建一个很大的实体类对象,我们只想解析json数据中的某个字段做业务处理,代码如下:
package main
import (
"fmt"
"github.com/json-iterator/go"
"strconv"
"strings"
)
//方法1:获取指定字段的值(参数1:字段路径,参数2:解析后的数据)
func GetJsonFieldValue(path []string, data map[string]interface{}) (interface{}, bool) {
if v, ok := data[path[0]]; ok == true {
if len(path) == 1 {
return v, true
} else {
value, ok := GetJsonFieldValue(path[1:], v.(map[string]interface{}))
return value, ok
}
} else {
return nil, false
}
}
//方法2:获取指定字段的值(参数1:字段路径,参数2:原始json数据)
func GetFieldFromJson(path []string, value []byte) string {
var temp jsoniter.Any
for i, v := range path {
if i == 0 {
temp = jsoniter.Get(value, v)
if temp == nil {
return ""
}
} else {
temp = temp.Get(v)
if temp == nil {
return ""
}
}
}
switch temp.ValueType() {
case jsoniter.InvalidValue, jsoniter.NilValue, jsoniter.BoolValue, jsoniter.ArrayValue, jsoniter.ObjectValue:
return ""
case jsoniter.StringValue:
return temp.ToString()
case jsoniter.NumberValue:
return strconv.Itoa(temp.ToInt())
}
return ""
}
func main() {
//通过原始数据获取指定字段值
res := GetFieldFromJson(strings.Split("commonInfo/Sent", "/"), []byte(Data))
fmt.Println("res:", res)
dataBuf := make(map[string]interface{})
err := jsoniter.Unmarshal([]byte(Data), &dataBuf)
if err != nil {
fmt.Printf("Json解析失败!error info:%v\n", err, Data)
return
}
fmt.Println("Json解析成功")
//1层
value, ok := dataBuf["SentType"].(string)
if ok {
fmt.Println("value:", value)
} else {
fmt.Println("not found")
}
filed1 := "SentType"
value1, ok := GetJsonFieldValue(strings.Split(filed1, "/"), dataBuf)
if ok {
fmt.Println("value1:", value1.(string))
} else {
fmt.Println("value1 not found")
}
//多层
filed2 := "commonInfo/Sent"
value2, ok := GetJsonFieldValue(strings.Split(filed2, "/"), dataBuf)
if ok {
fmt.Println("value2:", value2.(string))
} else {
fmt.Println("value2 not found")
}
}
var Data = `{
"SentType": "11",
"commonInfo": {
"operationId": "10012019111317041700000001",
"operationType": 1,
"operationTime": "2019-11-13 17:04:17",
"dataSource": null,
"Sent": "10"
},
"metaData": {
"type": 1,
"name": "常口",
"libraryId": null,
"libraryMark": "1",
"data": [
{
"id": "218906b5-f483-4beb-b8e7-b5b589cf4a40",
"credentialNumber": "7787ce86c379a6d0f604569b7e3ea1ea",
"cityCode": null,
"presentPlace": "650103",
"communityCode": null,
"createDate": "2019-11-13 17:04:17",
"name": "房",
"featureValue": "",
"algorithmCode": "0204000100",
"picType": 1,
"picBase64": "",
"picUrl": "11",
"CRUD": 1
}
]
},
"timeLists": [
{
"serverID": "1001",
"serverName": "黑名单",
"startTime": "2019-11-13 17:04:17 278",
"sendTime": "2019-11-13 17:04:17 278"
}
]
}`
运行结果:
res: 10
Json解析成功
value: 11
value1: 11
value2: 10
总结:建议使用方法2,无需判断原始字段类型,最终返回string。