Go知识点之随便记记(七)— Json,Xml数据格式转换

学习资料来自

GitHub - unknwon/the-way-to-go_ZH_CN: 《The Way to Go》中文译本,中文正式名《Go 入门指南》

数据格式转换

1、JSON(json包)

序列化(其它->json)

1)Json与Go的类型对应

(Go与Json的对应)

  • bool — boolean
  • float64 — number
  • string — string
  • nil — null

2)结构体 -> Json编码

将数据转为Json格式

(1)func Marshal(v interface{}) ([]byte, error) :对数据进行Json编码,转换为Json格式

(2)MarshalforHTML()函数:针对html数据

(3)func NewEncoder(w io.Writer) *Encoder :返回Encoder类型的指针

(4)Encode(v interface{}) 由(3)中Encoder类型的指针调用,可将数据对象v的json编码写入 (3)中的w中

3)仅验证通过的数据允许编码为json:需编码为map类型再转换

  • key必为字符串
  • Channel,复杂类型和函数类型不能被编码
  • 不支持循环数据结构
  • 指针可以被编码(对指针指向的值进行编码)

反序列化(json—>其它)

1)确定解码后类型:func Unmarshal(data []byte, v interface{}) error:将data解码为数据结构,存储至v(匹配的字段填充数据。未匹配字段直接忽略,不报错。)

2)不确定解码后类型:使用map[string]interface{}类型存储

// 数据
b := []byte(`{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`)
// 解码
var f interface{}
err := json.Unmarshal(b, &f)
// 解码结果

map[string]interface{} {
	"Name": "Wednesday",
	"Age":  6,
	"Parents": []interface{} {
		"Gomez",
		"Morticia",
	},
}

---

2、XML(encoding/xml包)

1)整体与Json类似,使用 xml.Marshal() 和 xml.Unmarshal()进行编码和解码。

2)包中定义 XML 标签:StartElement,Chardata(这是从开始标签到结束标签之间的实际文本),EndElement,Comment,Directive 或 ProcInst。

3)结构解析器:NewParser,方法有 io.Reader 。还有一个 Token() 方法返回输入流里的下一个 XML token。

4)输入流的结尾返回(nil,io.EOF)

---

3、编码和解码流(文件读写)

func NewDecoder(r io.Reader) *Decoder
func NewEncoder(w io.Writer) *Encoder
//解码
func NewDecoder(r io.Reader) *Decoder
func (dec *Decoder) Decode(v interface{}) error
//编码
func NewEncoder(w io.Writer) *Encoder
func (enc *Encoder) Encode(v interface{}) error

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值