学习资料来自
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