duancan65665 2016-02-05 02:02
浏览 4
已采纳

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

I'm following up on Golang Decoding Generic JSON Objects to One of Many Formats as a way to unmarshal generic json. I'm going to have a multitude of different types tho which can be added by others, so hardcoding case statements is not feasible.

I also don't want to hardcode the type as a string, but let the ones using the library chose the "lookup" name, in case they want to rename their underlying structs later.

I am basically looking for something like this:

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
}

I have this feeling that I'm overthinking the whole Problem. Or that I'm trying to bend Go into something that conflicts with its underlying philosophy. I'm very open and thankful for any advice that suggests a different approach to the whole Problem

  • 写回答

1条回答 默认 最新

  • doujizhong8352 2016-02-05 03:38
    关注

    Have types be a map[string]myInterface, and to register a type, have callers store an empty value of that type (not a reference) into the map. Then, to unmarshal, you can "get the type" by copying the empty value out of the map, unmarshaling into it, and returning it (or a reference to it). The interface value will do the job of identifying which type is wanted. Plus, if users want to default some fields to non-zero/empty values in case they're not provided in the JSON, they can actually do that by storing those values within the struct in the type map.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥15 看一下OPENMV原理图有没有错误
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常
  • ¥15 Java,消息推送配置
  • ¥15 Java计划序号重编制功能,此功能会对所有序号重新排序,排序后不改变前后置关系。
  • ¥15 关于哈夫曼树应用得到一些问题