![](/img/trans.png)
[英]How to integrate two or more google-services.json file together for different google FCM service in same project
[英]How to use two JSON unmarshallers in the same project?
在使用 JSON 解組進行 POC 時,我需要根據 go 代碼中的某些條件使用兩個自定義 json 提供程序。
easyJson.unmarshal()
json.unmarshal()
我面臨的問題是因為我們導入了一個自定義的 easyJson 代碼, json.Unmarshal()
也將使用它,並且完整的應用程序被迫使用 easyJson 生成的代碼。
參考游樂場示例: https : //play.golang.org/p/VkMFSaq26Oc
我想在這里實現的是
if isEasyJsonEnabled {
easyjson.Unmarshal(inp1, inp2)
} else{
json.Unmarshal(inp1, inp2)
}
如您在easyJson
代碼中所見,上述條件不起作用:兩個解組器都將使用easyJson
代碼。 在此處指導我或建議此處是否需要任何其他信息。
您可以創建一個新的不同類型來包裝您當前的類型。
就像是
package main
import (
"encoding/json"
"fmt"
"os"
)
type Foo struct {
Bar string `json:"bar"`
}
type Bar Foo
// UnmarshalJSON implements custom unmarshaler, similar to the one generated by easyjson.
// This is a hypotethical case to demonstrate that UnmarshalJSON is automatically called
// when we are using encoding/json.Unmarshal.
//
// Try commenting this method and see the difference!
func (f *Foo) UnmarshalJSON(b []byte) error {
f.Bar = "I'm using custom unmarshaler!"
return nil
}
func main() {
var f Foo
b := []byte(`{"bar":"fizz"}`)
var bar Bar
err := json.Unmarshal(b, &bar)
if err != nil {
fmt.Println("ERR:", err)
os.Exit(1)
}
f = Foo(bar)
fmt.Printf("Result: %+v", f)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.