測試一下golang的json序列化Marshal

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
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}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.