avatar

Catalog
Go 处理PHP serialize序列化数据 反序列化 Go php serialize to json

代码地址 https://github.com/haoleiqin/Go-PHP-serialize-json
php serialize to json (Go)

plaintext
1
2
3
4
5
6
7
8
9
10
Array
(
[0] => Array
(
[id] => 1
[price] => 80
[name] => 一个名字
)

)

phpserialize string

plaintext
1
a:1:{i:0;a:3:{s:2:"id";i:1;s:5:"price";i:80;s:4:"name";s:12:"一个名字";}}

to json

plaintext
1
[{"Id":1,"Price":80,"Name":"一个名字"}]

run go test

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
54
55
56
57
58
59
60
package main

import (
"encoding/json"
"fmt"
"net/url"

"github.com/haoleiqin/phpserialize"
)

type serObj struct {
}
type serializeStruct struct {
Id int64
Price int64
Name string
}

func (serObj *serObj) Phpserialize2Json(serialize string) (jsonres string) {
var serializeMap []interface{}
err := phpserialize.Unmarshal([]byte(serialize), &serializeMap)
if err != nil {
fmt.Println(err)
}
var convertData serializeStruct
var jsonMap []serializeStruct
var jsonRes string
listKey := 0
for _, list := range serializeMap {
listKey += 1
keyIndexNumCount := 0
for vkey, value := range list.(map[interface{}]interface{}) {
keyIndexNumCount += 1
switch vkey {
case "id":
convertData.Id = value.(int64)
case "price":
convertData.Price = value.(int64)
case "name":
convertData.Name = value.(string)
paramNums := 3
if keyIndexNumCount == paramNums {
jsonMap = append(jsonMap, convertData)
if listKey >= len(serializeMap) {
data, errsjon := json.Marshal(jsonMap)
if errsjon != nil {
fmt.Println(errsjon)
}
enEscapeUrl, queryUnescapeErr := url.QueryUnescape(string(data))
if queryUnescapeErr != nil {
fmt.Println(queryUnescapeErr)
}
jsonRes = enEscapeUrl
}
}
}
}
}
return jsonRes
}
Author: Qin
Link: https://qinhaolei.com/posts/59073/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Reward
  • WechatPay
    WechatPay
  • AliPay
    AliPay
  • Bitcoin
    Bitcoin

Comment