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

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本