简体   繁体   中英

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.

  1. easyJson.unmarshal()
  2. 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.

Refer playground example: 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. 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM