标签:
func test_json() { x, _ := json.Marshal([]string{"aaa:123", "bbb:456"}) fmt.Println(x) var caps []string json.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 := 0 for 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 = i continue } c, size := utf8.DecodeRuneInString(s[i:]) if c == utf8.RuneError && size == 1 { if start < i { e.WriteString(s[start:i]) } e.WriteString(`\ufffd`) //这种类型打了标志 i += size start = i continue } // 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 += size start = i continue } i += size } if start < len(s) { e.WriteString(s[start:]) } e.WriteByte(‘"‘) return e.Len() - len0, nil }
标签:
原文地址:http://my.oschina.net/yang1992/blog/508257