如何在同一项目中使用两个 JSON 解组器?

How to use two JSON unmarshallers in the same project?

在使用 JSON 解组进行 POC 时,我需要根据 go 代码中的某些条件使用两个自定义 json 提供程序。

  1. easyJson.unmarshal()
  2. json.unmarshal()

我面临的问题是因为我们导入了自定义 easyJson 代码,json.Unmarshal() 也将使用该代码并且整个应用程序被迫使用 easyJson 生成的代码。

参考游乐场示例:https://play.golang.org/p/VkMFSaq26Oc

我想在这里实现的是

if isEasyJsonEnabled {
     easyjson.Unmarshal(inp1, inp2)
    } else{
     json.Unmarshal(inp1, inp2)     
}

如您在 playground 代码中所见,上述条件无效:两个解组器都将使用 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)
}