2016-02-05 41 views
1

我正在跟進Golang Decoding Generic JSON Objects to One of Many Formats作爲解組泛型json的一種方式。我將會有許多不同類型的tho可以被其他人添加,所以硬編碼的case語句是不可行的。使用類型查找映射反編組泛型json

我也不想將該類型硬編碼爲字符串,但讓那些使用庫的人選擇「查找」名稱,以防他們稍後重新命名其基礎結構。

我基本上是在尋找這樣的事情:

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 
} 

我有這種感覺,我的得太多整個問題。或者,我正試圖彎曲與其底層哲學衝突的事物。我非常開放並且非常感謝任何意見,建議採取不同的方法來解決整個問題

回答

0

typesmap[string]myInterface,並且要註冊一個類型,請調用者將該類型的空值(不是引用)存儲到地圖。然後,爲了解組,可以通過將空值從映射中複製出來,解組並將其返回(或引用它)來「獲取類型」。界面值將完成識別需要哪種類型的工作。此外,如果用戶想要將某些字段默認爲非零/空值(如果它們未在JSON中提供),則實際上可以通過將這些值存儲在類型映射中的結構中來實現。

+0

接受這個答案是因爲它完成了工作。不過,我現在改變了我的代碼,所以它不再依賴於類型映射 – paukul