前言
xutil
今天分享的文章源自于开源项目jinzaigo/xutil
的封装。
PHP转Go
我和劲仔都是PHP转Go,身边越来越多做PHP的朋友也逐渐在用Go进行重构,重构过程中,会发现php的json解析操作(系列化与反序列化)是真的香,弱类型语言的各种隐式类型转换,很大程度的减低了程序的复杂度。
JSON解析实践
案例:用go重构的服务,对接的上游还是php服务,这时php接口输出的json串为{"name":"AppleWatchS8","price":"3199"}
。
标准库encoding/json
package main
import (
"encoding/json"
"fmt"
type ProductInfo struct {
Name string `json:"name"`
Price float32 `json:"price"`
}
func main( {
str := "{"name":"AppleWatchS8","price":"3199"}"
data := ProductInfo{}
if err := json.Unmarshal([]byte(str, &data; err != nil {
fmt.Println("error: " + err.Error(
} else {
fmt.Println(data
}
}
//输出结果
//error: json: cannot unmarshal string into Go struct field ProductInfo.price of type float32
显然,使用go标准库做json解析,是应对不了这种类型不一致的情况的。下面则借助第三方库的能力来做处理
第三方库json-iterator
执行速度:jsoniter 的 Golang 版本可以比标准库(encoding/json)快 6 倍之多
完全兼容标准库,也就是API用法完全一样,原有逻辑代码不需要改动,只需要替换import包名
安装方式:
go get -u github.com/json-iterator/go
具体代码实现:
package main
import (
"fmt"
jsoniter "github.com/json-iterator/go"
"github.com/json-iterator/go/extra"
var json = jsoniter.ConfigCompatibleWithStandardLibrary
func init( {
extra.RegisterFuzzyDecoders( //开启PHP兼容模式
}
type ProductInfo struct {
Name string `json:"name"`
Price float32 `json:"price"`
}
func main( {
str := "{"name":"AppleWatchS8","price":"3199"}"
data := ProductInfo{}
if err := json.Unmarshal([]byte(str, &data; err != nil {
fmt.Println("error: " + err.Error(
} else {
fmt.Println(data
}
}
//输出结果
//{AppleWatchS8 3199}
看输出结果,会发现用了这个库并且开启了PHP兼容模式,json中price字段string类型,就会自动转换为结构体中定义的float32类型。
收集到开源工具包xutil中
这个第三库用起来如此方便,那肯定是要收录进来的,将替换包名、手动开启PHP兼容模式、还有常用的API方法(系列化与反序列化操作),统一封装进来,简化使用流程。
以上这个思路也适用于大家封装自己内部使用的工具库。
go get -u github.com/jinzaigo/xutil
之后,import github.com/jinzaigo/xutil/xjson,
示例代码:
package main import ( "fmt" "github.com/jinzaigo/xutil/xjson" type ProductInfo struct { Name string `json:"name"` Price float32 `json:"price"` } func main( { str := "{"name":"AppleWatchS8","price":"3199"}" data := ProductInfo{} if err := xjson.Unmarshal([]byte(str, &data; err != nil { fmt.Println("error: " + err.Error( } else { fmt.Println(data } }
总结
业务系统从php转go,或go对接php服务,都会遇到这个因为数据类型不一致导致json解析错误的共性问题。
收录到开源项目中,更好的帮助到需要的朋友,欢迎使用、star与PR共同建设。
https://github.com/jinzaigo/xutil