登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-02-17 19:15:23 193浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《如何在一个项目中同时使用两个 JSON 解析器?》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

在使用 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)     
}

如演示代码中所示,上述条件不起作用:两个解组器都将使用 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)
}

以上就是《如何在一个项目中同时使用两个 JSON 解析器?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>