JSON、XML序列化与反序列化

序列化
pa := &Address{"家","太原","中国"}
wa := &Address{"工作","昆山","江苏"}
vc := &VCard{"王","剑英",[]*Address{pa,wa},"啊哈哈"}
js,_ := json.Marshal(vc)//编码生成js([]byte),在Web中使用MarshalforHTML
fmt.Println(string(js))
file,_ := os.OpenFile("vcard.json",os.O_CREATE|os.O_WRONLY,0666)
defer file.Close()
encoder := json.NewEncoder(file)//生成向文件输出的输出流
encoder.Encode(js)//输出js
JSON 与 Go 类型对应如下:
bool 对应 JSON 的 boolean
float64 对应 JSON 的 number
string 对应 JSON 的 string
nil 对应 JSON 的 null
不是所有的数据都可以编码为 JSON 类型:只有验证通过的数据结构才能被编码:
JSON 对象只支持字符串类型的 key;要编码一个 Go map 类型,map 必须是 map[string]T(T是 json 包中支持的任何类型)
Channel,复杂类型和函数类型不能被编码
不支持循环数据结构;它将引起序列化进入一个无限循环
指针可以被编码,实际上是对指针指向的值进行编码(或者指针是 nil)

反序列化:
UnMarshal,把JSON解码为数据结构
func Unmarshal(data []byte,v interface{}) error
编码后的数据是js,解码时,首先创建数据结构用来保存解码的数据 v interface。
并调用Unmarshal(js,&v),解析[]byte中的Json数据并将结果存入指针&v指向的数据结构

解码任意的数据
Json包使用map[string]interface{}储存任意的JSON对象和数组;
其可以被反序列化为任何的JSON blob存储到接口值中。

b := []byte(`{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`)

var f interface{}
json.Unmarshal(b,&f)
m := f.(map[string]interface{})
for k,v := range m{
switch vv := v.(type) {
case string:
fmt.Println(k,"is string",vv)
case float64:
fmt.Println(k,"is float",vv)
case []interface{}:
fmt.Println(k,"is an arry")
for i, u := range vv{
fmt.Println(i,u)
}
default:
fmt.Println(k,"is of a type I don't know to handle")

编码和解码流:
json包提供Decoder和Encoder类型来支持常用JSON数据流读写。
NewDecoder相当于io.Reader
func NewDecoder(r io.Reader) *Decoder
NewEncoder相当于io.Writer
func NewEncoder(w io.writer) *Encoder
把JSON直接写入文件,使用json.NewEncoder后再使用Encode().
从文件中读JSON,使用json.NewDecoder后再事项Decode()

decode()方法怎么使用,看看api
反序列化。看看别人怎么做的吧

xml的反序列化
package main

import (
"encoding/xml"
"fmt"
"strings"
)

var t, token xml.Token
var err error

func main() {
input := "<Person><FirstName>Laura</FirstName><LastName>Lynn</LastName></Person>"
inputReader := strings.NewReader(input)
p := xml.NewDecoder(inputReader)

for t, err = p.Token(); err == nil; t, err = p.Token() {
switch token := t.(type) {
case xml.StartElement:
name := token.Name.Local
fmt.Printf("Token name: %s ", name)
for _, attr := range token.Attr {
attrName := attr.Name.Local
attrValue := attr.Value
fmt.Printf("An attribute is: %s %s ", attrName, attrValue)
// ...
}
case xml.EndElement:
fmt.Println("End of token")
case xml.CharData:
content := string([]byte(token))
fmt.Printf("This is the content: %v ", content)
// ...
default:
// ...
}
}
}

EnCoder:自动编码(但是使用的时候必须是纯Go环境,还贴心的加了一个换行)
DeCoder:自动解码到对象

不是纯Go环境,可以通过Marshal将对象(struct转化为json的数组)转化为字节数组
然后存到文件中。

原文地址:https://www.cnblogs.com/mcmx/p/11390874.html