使用类型查找映射解组通用 json

我正在跟进Golang 将通用 JSON 对象解码为多种格式之一,作为解组通用 json 的一种方式。我将有许多不同的类型,其他人可以添加这些类型,因此硬编码 case 语句是不可行的。


我也不想将类型硬编码为字符串,但让使用库的人选择“查找”名称,以防他们以后想重命名其底层结构。


我基本上是在寻找这样的东西:


type myInterface interface {

  Something() // irrelevant, just to show you It's not about interface{}

}


type myBar struct {}       // fulfils myInterface

type mySomething struct {} // fulfils myInterface


var types = make(map[string]type) // <--- Obvious Pseudo code ;)

types["foo:bar"] = myBar       // done by whoever uses the library

types["1230988"] = mySomething // ...


type storageWrapper struct {

  Type string

  Data json.RawMessage

}


func loadSomething(id string) myInterface {

  buf := db.load(id) // pseudo code but you get the idea

  sw := &storageWrapper{}

  json.Unmarshal(buf, sw)


  // now the interesting part

  targetType := types[sw.Type]

  thing := &targetType{}

  json.Unmarshal(sw.Data, thing)

  return thing

}

我有一种感觉,我把整个问题想得太多了。或者我试图将 Go 转变为与其基本哲学相冲突的东西。我非常开放并感谢任何建议对整个问题提出不同的方法


烙印99
浏览 120回答 1
1回答

MMTTMM

必须types是 a&nbsp;map[string]myInterface,并注册一个类型,让调用者将该类型的空值(不是引用)存储到映射中。然后,要解组,您可以通过从映射中复制空值、解组到其中并返回它(或对它的引用)来“获取类型”。接口值将完成识别所需类型的工作。另外,如果用户希望将某些字段默认为非零/空值,以防它们未在 JSON 中提供,他们实际上可以通过将这些值存储在类型映射的结构中来实现。
打开App,查看更多内容
随时随地看视频慕课网APP