根据golang中的条件执行自解组方法或默认解组方法

I am a novice in golang. I have a struct Item .

type Item Struct{
   ...
}

and I know it has a default UnmarshalJSON method.
Now I want to unmarshal data to it.

For the data may has two different format. So my expection as below:

if condition {
    //execute default UnmarshalJSON
    json.Unmarshal(data, &item) 
}else{
    //execute my own UnmarshalJSON
    json.Unmarshal(data, &item) 
}

this is my own UnmarshalJSON.

func (item *Item) UnmarshalJSON(data []byte) error{
   ...
}

Maybe myself UnmarshalJSON will override default, so the two method could not be present at the same time. I want to know how to solve this kind problem which Unmarshal two different format data into one struct.

Use an interface whatever be the format you are getting from the json response and unmarshal the response into interface as:

func main(){
    var result interface{}
    if err := json.Unmarshal(jsonbytes, &result); err != nil{
         fmt.Println(err)
    }
}

Then use type assertion to fetch the value underlying the interface. But I think in your case if you do not the underlying type of a key. Better is to use recursion to fetch the value.

func fetchValue(value interface{}) {
    switch value.(type) {
    case string:
        fmt.Printf("%v is an interface 
 ", value)
    case bool:
        fmt.Printf("%v is bool 
 ", value)
    case float64:
        fmt.Printf("%v is float64 
 ", value)
    case []interface{}:
        fmt.Printf("%v is a slice of interface 
 ", value)
        for _, v := range value.([]interface{}) { // use type assertion to loop over []interface{}
            fetchValue(v)
        }
    case map[string]interface{}:
        fmt.Printf("%v is a map 
 ", value)
        for _, v := range value.(map[string]interface{}) { // use type assertion to loop over map[string]interface{}
            fetchValue(v)
        }
    default:
        fmt.Printf("%v is unknown 
 ", value)
    }
}

Working Code on Go playground

Above code will let you to fetch any type of value that is parsed into an interface.

Note:

In golang it is defined that when you unmarshal unknown json into an interface. It will be converted into following types:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays // slice of interface{}
map[string]interface{}, for JSON objects
nil for JSON null