duanletao9487 2018-10-23 09:22
浏览 46
已采纳

根据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.

  • 写回答

1条回答 默认 最新

  • drbd65446 2018-10-23 09:28
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)