Go 和 PHP 通信是痛苦的,PHP 这个神奇的 json ,各种奇奇怪怪的 json 都能生成出来,如果一开始就奇怪直接用interface也就算了,最可怕那种是类型会变。
在用 Go 重构 PHP 项目的时候,两个项目往往会共享存储,我们在生成缓存的时候,也经常把数据转成 json 去存储。
我大 PHP 生成 json 有这么两个另 Go 崩溃的事情,一个是 int 和 string 的不确定,第二个就是 PHP array是空的时候,序列化出来是[],但是不为空的时候,序列化出来的是{“key”:“value”}。
但是 jsoniter (https://github.com/json-iterator/go、http://jsoniter.com/go-tips.cn.html)对可以做模糊转换,省了很多事情。
看个例子
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21package main import ( "fmt" "github.com/json-iterator/go" "github.com/json-iterator/go/extra" ) func main() { extra.RegisterFuzzyDecoders() var i int var json = jsoniter.ConfigCompatibleWithStandardLibrary json.Unmarshal([]byte(`"1"`), &i) fmt.Printf("我是int %dn",i) var s string json.Unmarshal([]byte(`"1"`), &s) fmt.Printf("我是string %sn",s) var m map[string]interface{} jsoniter.UnmarshalFromString(`{}`, &m) fmt.Printf("我是map %sn",m) return }
结果
复制代码
1
2
3
4我是int 1 我是string 1 我是map map[]
如果没有 jsoniter ,断言写到手软也就算了,程序来几个panic,case study 写到手软才最惨。
当然了 jsoniter 也不是万能的,它也仅仅能处理这两种比较常见的,遇到其他奇葩 json 估计只能断言、switch v.(type) case 写到手软了。
更多架构、PHP、GO相关踩坑实践技巧请关注我的公众号:PHP架构师
最后
以上就是失眠月光最近收集整理的关于Go 重构 PHP 项目的一个神器 jsoniter的全部内容,更多相关Go内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复