go - 反序列化未知的 Go 的 gob blob

标签 go serialization reflection gob reflect

我有未知类型的采空区。有没有办法打印出来在里面查看?

可能有 gob.Debug 但我不可用 https://golang.org/src/encoding/gob/debug.go

谷歌搜索建议使用 DecodeValue 但它需要初始化 reflect.Value 如果我得到未知的 gob blob,那么我无法传递未知类型的初始化值

https://play.golang.org/p/OWxX1kPJ6Qa

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "reflect"
)


func encode1() []byte {

    x := "123"

    buf := &bytes.Buffer{}
    enc := gob.NewEncoder(buf)
    err := enc.Encode(x)
    if err != nil {
        panic(err)
    }
    return buf.Bytes()

}

func decode1(b1 []byte) {
    var x string
    dec := gob.NewDecoder(bytes.NewBuffer(b1))
    err := dec.Decode(&x)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", x)
}

func decode2(b1 []byte) {
//  var x reflect.Value
    x := reflect.New(reflect.TypeOf(""))
    dec := gob.NewDecoder(bytes.NewBuffer(b1))
    err := dec.DecodeValue(x)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", x)
    fmt.Printf("%#v\n", reflect.Indirect(x))
}

func main() {
    b1 := encode1()
    decode1(b1)
    decode2(b1)
}

最佳答案

你需要Register编码解码前的类型

Register records a type, identified by a value for that type, under its internal type name. That name will identify the concrete type of a value sent or received as an interface variable. Only types that will be transferred as implementations of interface values need to be registered. Expecting to be used only during initialization, it panics if the mapping between types and names is not a bijection.

关于go - 反序列化未知的 Go 的 gob blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53467734/

相关文章:

go - 如何实现 goroutines 的管道?

go - 如何导入项目特定的 go 包,同时为完全不同的项目通用的 go 包维护一个单独的位置?

go - 协会不使用测试条目

java - Jackson - 通用 TreeSet 未序列化

C# dynamic + System.Reflection.Emit = 不混用?

json - 自定义 Json 编码(marshal)处理

c# - XML 序列化动态对象

hibernate - 如何在 Grails 中持久保存数据库中的闭包?

java - 如何使用反射获取注释类名称、属性值

C# - 制作一个接受任何类型的通用 foreach 方法?