简体   繁体   中英

How can I make my unmarshall function in golang handle multiple types?

I'm using the json.unmarshalling function in golang to decode some JSON responses we got from the API. How do I make it handle multiple types?

The response we receive are always status code and a message, but the json field have different names. Sometimes these two fields are called code and message and sometimes they are called statuscode and description, depending on what we query.

say that we queries Apple and this is simply solved by creating an Apple type struct like this:

type Apple struct {
    Code        int    `json:"code"`
    Description string `json:"message"`
}

But when we query Peach, the json we got back is no longer code and message anymore, the field names became statuscode and description. So we will need the following:

type Peach struct {
    Code        int    `json:"statuscode"`
    Description string `json:"description"`
}

Potentially, we need to set up 50 more types and write duplicate for 50 times?? There MUST be a better way to do this. Unfortunately I'm new to Golang and don't know how polymorphism works in this language. Please help.

As far as I know , You should always decode into structs to benefit from go static types , the methods attached to that struct and perhaps be able to validate your responses with a package like validator , but you could always parse the JSON body into a map like this :

// JsonParse parses the json body of http request
func JsonParse(r *http.Request) (map[string]interface{}, error) {
    // Read the r.body into a byte array
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        return nil, err
    }
    // Make a map of String keys and Interface Values
    b := make(map[string]interface{})
    // Unmarshal the body array into the map
    err = json.Unmarshal(body, &b)
    if err != nil {
        return nil, err
    }
    return b, nil
}

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