golang原生的json解析庫(kù),有時(shí)候用起來(lái)一點(diǎn)都不方便豪嗽,自己簡(jiǎn)單封裝了一下,看下測(cè)試用例
var jsonStr2 = `{"int":1,"bool":false,"string":"123","object":{"key":111}}`
func TestJsonObject(t *testing.T) {
object, err := NewJsonObject(jsonStr2)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(object.GetFloat64("int"))
fmt.Println(object.GetBool("bool"))
fmt.Println(object.GetString("string"))
// 想要獲取內(nèi)層數(shù)據(jù),中間加點(diǎn)即可
fmt.Println(object.GetFloat64("object.key"))
}
測(cè)試結(jié)果
1 <nil>
false <nil>
123 <nil>
111 <nil>
這里貼出代碼:
package jsonlib
import (
"encoding/json"
"errors"
"strings"
)
var (
ErrNil = errors.New("error key not exist") // key所對(duì)應(yīng)的值不存在
ErrFormat = errors.New("error formart") // 類型轉(zhuǎn)換錯(cuò)誤
)
type JsonObject struct {
data map[string]interface{}
}
// NewJsonObject 創(chuàng)建一個(gè)json對(duì)象
func NewJsonObject(str string) (*JsonObject, error) {
jsonObject := new(JsonObject)
err := json.Unmarshal([]byte(str), &jsonObject.data)
if err != nil {
return nil, err
}
return jsonObject, nil
}
func (o *JsonObject) getValue(key string) (interface{}, error) {
m := o.data
keys := strings.Split(key, ".")
var (
value interface{}
ok = false
)
for i := 0; i < len(keys)-1; i++ {
value, ok = m[keys[i]]
if !ok {
return nil, ErrNil
}
m, ok = value.(map[string]interface{})
if !ok {
return nil, ErrFormat
}
}
value, ok = m[keys[len(keys)-1]]
if !ok {
return nil, ErrNil
}
return value, nil
}
// GetBool 獲取Bool值
func (o *JsonObject) GetBool(key string) (bool, error) {
value, err := o.getValue(key)
if err != nil {
return false, err
}
result, ok := value.(bool)
if !ok {
return false, ErrFormat
}
return result, nil
}
// GetFloat64 獲取float64值
func (o *JsonObject) GetFloat64(key string) (float64, error) {
value, err := o.getValue(key)
if err != nil {
return 0, err
}
result, ok := value.(float64)
if !ok {
return 0, ErrFormat
}
return result, nil
}
// GetString 獲取string值
func (o *JsonObject) GetString(key string) (string, error) {
value, err := o.getValue(key)
if err != nil {
return "", err
}
result, ok := value.(string)
if !ok {
return "", ErrFormat
}
return result, nil
}
// GetBool 獲取Bool值
func GetBool(str string, key string) (bool, error) {
object, err := NewJsonObject(str)
if err != nil {
return false, err
}
return object.GetBool(key)
}
// GetFloat64 獲取float64值
func GetFloat64(str string, key string) (float64, error) {
object, err := NewJsonObject(str)
if err != nil {
return 0, err
}
return object.GetFloat64(key)
}
// GetString 獲取string值
func GetString(str string, key string) (string, error) {
object, err := NewJsonObject(str)
if err != nil {
return "", err
}
return object.GetString(key)
}