這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
func test_json() {x, _ := json.Marshal([]string{"aaa:123", "bbb:456"})fmt.Println(x)var caps []stringjson.Unmarshal(x, &caps)fmt.Println(caps)}//輸出結果 -------------------------------[91 34 97 97 97 58 49 50 51 34 44 34 98 98 98 58 52 53 54 34 93][aaa:123 bbb:456]//把每個字元都轉成對應ascill數值
通過反射找到具體的編碼器,此例子對應編碼器為string
func (e *encodeState) string(s string) (int, error) {len0 := e.Len()e.WriteByte('"')start := 0for i := 0; i < len(s); {if b := s[i]; b < utf8.RuneSelf {if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {i++continue}if start < i {e.WriteString(s[start:i])}switch b {case '\\', '"':e.WriteByte('\\')e.WriteByte(b)case '\n':e.WriteByte('\\')e.WriteByte('n')case '\r':e.WriteByte('\\')e.WriteByte('r')case '\t':e.WriteByte('\\')e.WriteByte('t')default:// This encodes bytes < 0x20 except for \n and \r,// as well as <, > and &. The latter are escaped because they// can lead to security holes when user-controlled strings// are rendered into JSON and served to some browsers.//這種類型打了標誌e.WriteString(`\u00`)e.WriteByte(hex[b>>4])e.WriteByte(hex[b&0xF])}i++start = icontinue}c, size := utf8.DecodeRuneInString(s[i:])if c == utf8.RuneError && size == 1 {if start < i {e.WriteString(s[start:i])}e.WriteString(`\ufffd`) //這種類型打了標誌i += sizestart = icontinue}// U+2028 is LINE SEPARATOR.// U+2029 is PARAGRAPH SEPARATOR.// They are both technically valid characters in JSON strings,// but don't work in JSONP, which has to be evaluated as JavaScript,// and can lead to security holes there. It is valid JSON to// escape them, so we do so unconditionally.// See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.if c == '\u2028' || c == '\u2029' {if start < i {e.WriteString(s[start:i])}e.WriteString(`\u202`) //這種類型打了標誌e.WriteByte(hex[c&0xF])i += sizestart = icontinue}i += size}if start < len(s) {e.WriteString(s[start:])}e.WriteByte('"')return e.Len() - len0, nil}