![ce6e17d431feebc119761b073e80c653.png](https://img-blog.csdnimg.cn/img_convert/ce6e17d431feebc119761b073e80c653.png)
前言
JSON 是目前最为流行的序列化手段,Go语言对于这些标准格式的编码和解码都有良好的支持,在Go语言中,encoding/json标准包处理json数据的序列化与反序列化问题。下面主要讲解序列化。
什么是序列化
序列化是将对象的状态信息转换为可以存储或传输的形式的过程。在序列化期间,对象将其当前状态写入到临时或持久性存储区。通过从存储区中读取对象的状态,重新创建该对象,则为反序列化。
各种类型的值
JSON是对JavaScript中各种类型的值——字符串、数字、布尔值和对象——Unicode本文编码。它可以用有效可读的方式表示基础数据类型和数组、slice、结构体和map等聚合数据类型。对于json的数据类型,go也会有对象的结构所匹配。大致对应关系如下:
![f4e02db182d450bb3d941fad621b8c21.png](https://img-blog.csdnimg.cn/img_convert/f4e02db182d450bb3d941fad621b8c21.png)
在解析 json 格式数据时,若以 interface{} 接收数据,需要按照以上规则进行解析。
序列化 Marshal()
序列化源码放在:
![5384f45cc61938152cf1a5cc49918bb4.png](https://img-blog.csdnimg.cn/img_convert/5384f45cc61938152cf1a5cc49918bb4.png)
json.Marshal()
// Marshal returns the JSON encoding of v.
//
// Marshal traverses the value v recursively.
// If an encountered value implements the Marshaler interface
// and is not a nil pointer, Marshal calls its MarshalJSON method
// to produce JSON. If no MarshalJSON method is present but the
// value implements encoding.TextMarshaler instead, Marshal calls
// its MarshalText method and encodes the result as a JSON string.
// The nil pointer exception is not strictly necessary
// but mimics a similar, necessary exception in the behavior of
// UnmarshalJSON.
//
// Otherwise, Marshal uses the following type-dependent default encodings:
//
// Boolean values encode as JSON booleans.
//
// Floating point, integer, and Number values encode as JSON numbers.
//
// String values encode as JSON strings coerced to valid UTF-8,
// replacing invalid bytes with the Unicode replacement rune.
// So that the JSON will be safe to embed inside HTML <script> tags,
// the string is encoded using HTMLEscape,
// which replaces "<", ">", "&", U+2028, and U+2029 are escaped
// to " ","u003e", "u0026", "u2028", and "u2029".
//