坑太多 自己慢慢看 不会的话 可以找我或者评论 ,我会一一回复
import (
"fmt"
"encoding/json"
)
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
type Product struct {
Name string
ProductID int64
Number int
Price float64
IsOnSale bool
}
func main {
p := &Product{}
p.Name = "err"
p.IsOnSale = true
p.Number = 10000
p.Price = 2499.00
p.ProductID = 1
datae, _ := json.Marshal(p)
//fmt.Println(string(datae)) {"Name":"err","ProductID":1,"Number":10000,"Price":2499,"IsOnSale":true}
data := string(datae)
response := &Response{
Code: 1,
Msg: "没有找到该用户或者密码错误",
Data: json.RawMessage(data),
}
b, err := json.Marshal(&response)
if err != nil {
fmt.Println("err", err)
}
//fmt.Println(string(b)) {"code":1,"msg":"没有找到该用户或者密码错误","data":{"Name":"err","ProductID":0,"Number":0,"Price":0,"IsOnSale":false}}
c.Data["json"] = string(b)
c.ServeJSON()
return
}
//打印语句
{"code":1,"msg":"没有找到该用户或者密码错误","data":{"Name":"err","ProductID":0,"Number":0,"Price":0,"IsOnSale":false}}
本文深入探讨了使用Go语言进行JSON数据序列化与反序列化的具体实现,包括自定义类型如Product和Response的定义,以及如何通过json.Marshal函数将这些类型转换为JSON格式的数据。同时,文章还展示了如何将Go结构体字段映射到JSON键名,以及处理复杂数据结构的技巧。
1069

被折叠的 条评论
为什么被折叠?



