[GO]json解析到结构体

package main

import (
    "encoding/json"
    "fmt"
)

type IT struct {
    Company string `json:"company"`
    Subjects []string `json:"subjects"`
    Isok bool `json:"isok"`
    Price float64 `json:"price"`
}

func main() {
    jsonbuf := `{"company":"zyg","isok":true,"price":5.55,"subjects":["go","python","java"]}`
    var tmp IT
    err := json.Unmarshal([]byte(jsonbuf), &tmp) //这个地方一下是取tmp的地址的,它需要对结构体进行更改,根据查看源码可以知道它的返回就一个err
    if err != nil {
        return
    }
    fmt.Printf("tmp = %+v\n", tmp)
}

执行的结果为

tmp = {Company:zyg Subjects:[go python java] Isok:true Price:5.55}  //这个结果没有问题,打印就是没有双引号的

如果其中只想需打印结果体的下面两行,只需要修改结构体为

type IT struct {
    //Company string `json:"company"`
    //Subjects []string `json:"subjects"`
    Isok bool `json:"isok"`
    Price float64 `json:"price"`
}

那么执行的结果自动的解析 为

tmp = {Isok:true Price:5.55}

猜你喜欢

转载自www.cnblogs.com/baylorqu/p/9663501.html