[]interface 接口类型转自定义结构体类型

话不多少,直接上代码

package main

import (
    "encoding/json"
    "fmt"
)

type CategoryType struct {
    CategoryID int `json:"category_id"`
    Type       int `json:"category_type"`
}

func main() {
    var category []CategoryType
    var categoryInter interface{}
    //categoryInter 这里的值其实是通过前端请求传进来的,如下所示,这样子的结构
    /*
            {"categorys": [
                {
                    "category_id": 1,
                    "category_type": -1
                },{
                    "category_id": 10,
                    "category_type": -1
                },{
                    "category_id": 7,
                    "category_type": 0
                },{
                    "category_id": 8,
                    "category_type": 0
                }
            ]}

            body, _ := ioutil.ReadAll(r.Body)
            defer r.Body.Close()
            reqJSON, err := simplejson.NewJson(body)
            categoryInter, _ := reqJSON.Get("categorys").Array()
    */
    //通过如下使用json序列化后转为对应的自定义结构
    c, err := json.Marshal(categoryInter)
    if err != nil {
        fmt.Println(err)
    }
    err = json.Unmarshal(c, &category) //此时这里category的数据类型是上方定义的[]CategoryType类型
    if err != nil {
        fmt.Println(err)
    }

    // 输出
    //  [ { 1, -1 },{ 10, -1 },{ 7, 0 },{ 8, 0 } ]
}
原文地址:https://www.cnblogs.com/s42-/p/14603047.html