dongyi3776 2019-07-15 22:33
浏览 120

如何在golang中使解组函数处理多种类型?

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.

  • 写回答

1条回答 默认 最新

  • dtv7174 2019-07-15 23:10
    关注

    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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog