温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

GO语言的json输入(反序列化)之interfac{}存储

发布时间:2020-07-23 10:46:45 来源:网络 阅读:1483 作者:ck_god 栏目:编程语言
// code_032_json_unmarshal_to_interface project main.go
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    b := []byte(`{
        "company":"tianmei",
        "subjects":[
            "Go",
            "C++",
            "Python",
            "Test"  
        ],
        "isok":true,
        "price":666.666
    }`)
    //备注:subjects:["Test",]后面没有元素了,还有逗号会报错的。

    var t interface{}
    err := json.Unmarshal(b, &t)
    if err != nil {
        fmt.Println("json err:", err)
    }
    fmt.Println(t)

    //使用断言判断类型
    m := t.(map[string]interface{})
    for k, v := range m {
        switch vv := v.(type) {
        case string:
            fmt.Println(k, "is string", vv)
        case int:
            fmt.Println(k, "is int", vv)
        case float64:
            fmt.Println(k, "is float64", vv)
        case bool:
            fmt.Println(k, "is bool", vv)
        case []interface{}: //slice类型的元素为interface{}接收
            fmt.Println(k, "is an array:")
            for i, u := range vv {
                fmt.Println(i, u)
            }
        default:
            fmt.Println(k, "is of a type I don't know to handle")
        }
    }
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI