gpt4 book ai didi

json - 将 JSON 解码为 Go 接口(interface){}

转载 作者:IT王子 更新时间:2023-10-29 01:39:55 26 4
gpt4 key购买 nike

我有一个带有 interface{} 类型字段的结构。在使用 memcached ( https://github.com/bradfitz/gomemcache ) 对其进行缓存的过程中,该结构被编码为 JSON,然后在从缓存中检索时将其解编回结构。生成的 interface{} 字段不可避免地指向类型为 map[string]interface{} 的对象(例如,interface{} 字段只能类型为 asserted as map[ string]interface{}),编码和解码过程没有保留类型信息。有没有办法在编码过程中保存这些信息,以便可以正确解码?还是我必须使用其他编解码器之类的?

type A struct {
value interface{}
}

type B struct {
name string
id string
}

func main() {
a := A{value: B{name: "hi", id: "12345"}}
cache.Set("a", a) // Marshals 'a' into JSON and stores in cache
result = cache.Get("a") // Retrieves 'a' from cache and unmarshals
fmt.Printf("%s", result.value.(B).name) // Generates error saying that
// map[string]interface{} cannot be type asserted as a 'B' struct
fmt.Printf("%s", result.value.(map[string]interface{})["name"].(string)) // Correctly prints "12345"
}

最佳答案

简短版,不,你不能那样做,尽管你没有多少选择。

  1. 更改 A.Value 以使用 B 而不是 interface{}
  2. A 添加一个函数,将 A.Value 从映射转换为 B(如果尚未 B<)/
  3. 使用 encoding/gob 并将字节存储在内存缓存中,然后使用 NewA(b []byte) *A 之类的函数将其转换回来。

要使用gob,你必须在编码/解码之前先用它注册每个结构,example :

func init() {
//where you should register your types, just once
gob.Register(A{})
gob.Register(B{})
}
func main() {
var (
buf bytes.Buffer
enc = gob.NewEncoder(&buf)
dec = gob.NewDecoder(&buf)
val = A{B{"name", "id"}}
r A
)
fmt.Println(enc.Encode(&val))
fmt.Println(dec.Decode(&r))
fmt.Printf("%#v", r)
}

关于json - 将 JSON 解码为 Go 接口(interface){},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24944338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com