go实现json解析

项目中需要使用json格式进行传输,json的序列化与反序列化
go的json解析需要使用encoding/json包
序列化,也就是由结构体转化为json string字符串。使用json.Marshal函数。
反序列化,就是将json string字符串转化为结构体。使用函数json.Unmarshal函数完成。

package main

import (
    "encoding/json"
    "fmt"
)
// 如果`json:"code"`去掉.会以字段名称为解析内容
type Result struct {
    Code    int    `json:"code"`
    Message string `json:"msg"`
}

func main() {
    var res Result
    res.Code    = 200
    res.Message = "success"

    //序列化
    jsons, errs := json.Marshal(res)
    if errs != nil {
        fmt.Println("json marshal error:", errs)
    }
    fmt.Println("json data :", string(jsons))

    //反序列化
    var res2 Result
    errs = json.Unmarshal(jsons, &res2)
    if errs != nil {
        fmt.Println("json unmarshal error:", errs)
    }
    fmt.Println("res2 code:", res2.Code)
    fmt.Println("res2 msg:", res2.Message)
}

运行结果如下:

 

 

案例:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
)

type ReturnData struct {
    Code int         `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data"`
}

func main() {
    JsonToArr()
    ArrToJson()
}

func JsonToArr() {
    line := "http://ce.ouluo.com/lzadmin.php/shop/sys_admin.debug/index.html"
    resp, err := http.PostForm(line, url.Values{"key": {"1"}})
    defer resp.Body.Close()
    if err != nil {
        fmt.Println(err.Error())
    }
    //fmt.Printf("输出类型为:%T\n", resp.Body)
    //fmt.Println(resp.Body) //返回的是io类型

    var buffer [512]byte           //固定大小的字节数组
    result := bytes.NewBuffer(nil) //声明一个可变大小的字节缓冲
    for {
        n, err := resp.Body.Read(buffer[0:])
        result.Write(buffer[0:n])
        if err != nil && err == io.EOF {
            break
        } else if err != nil {
            panic(err)
        }
    }

    fmt.Println(result.String()) //  {"code":0,"msg":"ok","data":{"key":"1"}}
    var data ReturnData
    json.Unmarshal([]byte(result.String()), &data)
    fmt.Println(data)
}

func ArrToJson() {
    data := ReturnData{0, "ok", map[string]string{"str": "haha"}}
    jsons, _ := json.Marshal(data)
    fmt.Println(string(jsons)) //{"code":0,"msg":"ok","data":{"str":"haha"}}

    line := "http://ce.ouluo.com/lzadmin.php/shop/sys_admin.debug/index.html"
    resp, _ := http.PostForm(line, map[string][]string{"q": {"1"}, "a": {"2"}})
    defer resp.Body.Close()
}

 

posted @ 2022-07-12 11:42  1O(∩_∩)O1  阅读(1109)  评论(0编辑  收藏  举报