Go语言的JSON输入(解码)(反序列化)之struct存储

栏目: Go · 发布时间: 7年前

// code_031_json_unmarshal project main.go
package main

import (
    "encoding/json"
    "fmt"
)

//可以使用json.Unmarshal()函数将JSON格式的文本解码为 Go 里面预期的数据结构。
//json.Unmarshal()函数的原型如下:
//    func Unmarshal(data []byte, v interface{}) error
//      该函数的第一个参数是输入,即JSON格式的文本(比特序列)
//      第二个参数表示目标输出容器,用于存放解码后的值。
type IT struct {
    Company string   `json:"company"`
    Subject []string `json:"subjects"`
    IsOk    bool     `json:"isok"`
    Price   float64  `json:"price"`
}

func main() {
    //第一:反序列化,完整字段。
    // b为从前端接收的数据
    b := []byte(`{
    "company":"alibaba",
     "subjects":[
        "Go",
        "C++",
        "Python",
        "Test"
    ],
    "isok":true,
    "price":666.666
    }`)

    var t IT                     //声明目标输出容器,用于存放解码后的值
    err := json.Unmarshal(b, &t) //调用函数,并传递两个参数:JSON的比特序列,目标输出的容器
    if err != nil {
        fmt.Println("json err:", err)
    }
    fmt.Println(t)

    //第二种:反序列化部分字段,如:Subjects字段。
    type IT2 struct {
        Subjects []string `json:"subjects"`
    }
    var t2 IT2
    err1 := json.Unmarshal(b, &t2)
    if err1 != nil {
        fmt.Println("json err:", err)
    }
    fmt.Println(t2)
}

以上所述就是小编给大家介绍的《Go语言的JSON输入(解码)(反序列化)之struct存储》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Chinese Authoritarianism in the Information Age

Chinese Authoritarianism in the Information Age

Routledge / 2018-2-13 / GBP 115.00

This book examines information and public opinion control by the authoritarian state in response to popular access to information and upgraded political communication channels among the citizens in co......一起来看看 《Chinese Authoritarianism in the Information Age》 这本书的介绍吧!

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具