[英]How to use two JSON unmarshallers in the same project?
While doing a POC with JSON unmarshalling I need to use two custom json providers based on some condition in my go code.在使用 JSON 解组进行 POC 时,我需要根据 go 代码中的某些条件使用两个自定义 json 提供程序。
easyJson.unmarshal()
json.unmarshal()
Problem I am facing is as we have a custom easyJson code imported, json.Unmarshal()
will also be using that and complete application is forced to use the easyJson generated code.我面临的问题是因为我们导入了一个自定义的 easyJson 代码,
json.Unmarshal()
也将使用它,并且完整的应用程序被迫使用 easyJson 生成的代码。
Refer playground example: https://play.golang.org/p/VkMFSaq26Oc参考游乐场示例: https : //play.golang.org/p/VkMFSaq26Oc
What I am trying to achieve here is我想在这里实现的是
if isEasyJsonEnabled {
easyjson.Unmarshal(inp1, inp2)
} else{
json.Unmarshal(inp1, inp2)
}
Above condition is not working as you can see in the playground code: both unmarshallers will use the easyJson
code.如您在
easyJson
代码中所见,上述条件不起作用:两个解组器都将使用easyJson
代码。 Guide me here or suggest if any other info needed here.在此处指导我或建议此处是否需要任何其他信息。
You can make a new distinct type that wraps your current type.您可以创建一个新的不同类型来包装您当前的类型。
Something like就像是
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.