一般interface{}都要类型确定,然后根据实际情况进行处理
/*
Created by jinhan on 17-8-16.
Tip: 一般interface{}都要类型确定,然后根据实际情况进行处理
Update:
*/
package main
import (
"fmt"
"github.com/yvasiyarov/php_session_decoder/php_serialize"
)
func main() {
str := `a:3:{s:4:"name";s:3:"tom";s:3:"age";s:2:"23";s:7:"friends";a:2:{i:0;a:1:{s:4:"name";s:5:"jerry";}i:1;a:1:{s:4:"name";s:4:"jack";}}}`
decoder := php_serialize.NewUnSerializer(str)
if result, err := decoder.Decode(); err != nil {
panic(err)
} else {
// 观察可以看出interface的类型是:
//php_serialize.PhpArray{"name":"tom", "age":"23", "friends":php_serialize.PhpArray{0:php_serialize.PhpArray{"name":"jerry"}, 1:php_serialize.PhpArray{"name":"jack"}}}
fmt.Printf("%T | %#v\n\n\n", result, result)
// 因为result是interface{},所以我们要确定它的类型,从上面打印的我们知道是php_serialize.PhpArray
realtype_result, ok := result.(php_serialize.PhpArray)
if ok {
// 确定类型后我们可以打印出map里的内容,如下:
/*
type PhpArray map[PhpValue]PhpValue
type PhpValue interface{}
*/
fmt.Printf("realtype_result:%T | %#v\n", realtype_result, realtype_result)
fmt.Printf("realtype_result['name']:%T | %#v\n", realtype_result["name"], realtype_result["name"])
fmt.Printf("realtype_result['age']:%T | %#v\n", realtype_result["age"], realtype_result["age"])
// 我们看出friends得出的结果是PhpValue,也就是interface{},并且真实类型是php_serialize.PhpArray
fmt.Printf("realtype_result['friends']:%T | %#v\n\n\n", realtype_result["friends"], realtype_result["friends"])
realtype_friends_result, ok := realtype_result["friends"].(php_serialize.PhpArray)
if ok {
// 你可以遍历看看
for k, v := range realtype_friends_result {
fmt.Printf("%T | %#v\n", k, k)
fmt.Printf("%T | %#v\n", v, v)
// 这里v也是一样了
vv, ok := v.(php_serialize.PhpArray)
if ok {
fmt.Printf("%T | %#v\n", vv["name"], vv["name"])
}
}
}
} else {
fmt.Println("类型错误,不是php_serialize.PhpArray")
}
}
}
输出是这样的:
php_serialize.PhpArray | php_serialize.PhpArray{"friends":php_serialize.PhpArray{0:php_serialize.PhpArray{"name":"jerry"}, 1:php_serialize.PhpArray{"name":"jack"}}, "name":"tom", "age":"23"}
realtype_result:php_serialize.PhpArray | php_serialize.PhpArray{"age":"23", "friends":php_serialize.PhpArray{0:php_serialize.PhpArray{"name":"jerry"}, 1:php_serialize.PhpArray{"name":"jack"}}, "name":"tom"}
realtype_result['name']:string | "tom"
realtype_result['age']:string | "23"
realtype_result['friends']:php_serialize.PhpArray | php_serialize.PhpArray{0:php_serialize.PhpArray{"name":"jerry"}, 1:php_serialize.PhpArray{"name":"jack"}}
int | 0
php_serialize.PhpArray | php_serialize.PhpArray{"name":"jerry"}
string | "jerry"
int | 1
php_serialize.PhpArray | php_serialize.PhpArray{"name":"jack"}
string | "jack"