加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

测试一下golang的json序列化Marshal

发布时间:2020-12-16 18:39:08 所属栏目:大数据 来源:网络整理
导读:functest_json(){x,_:=json.Marshal([]string{"aaa:123","bbb:456"})fmt.Println(x)varcaps[]stringjson.Unmarshal(x,caps)fmt.Println(caps)}//输出结果-------------------------------[913497979758495051344434989898585253543493][aaa:123bbb:456]//把
functest_json(){
	x,_:=json.Marshal([]string{"aaa:123","bbb:456"})
	fmt.Println(x)
	varcaps[]string
	json.Unmarshal(x,&caps)
	fmt.Println(caps)
}

//输出结果-------------------------------
[913497979758495051344434989898585253543493]
[aaa:123bbb:456]
//把每个字符都转成对应ascill数值

通过反射找到具体的编码器,此例子对应编码器为string

func(e*encodeState)string(sstring)(int,error){
	len0:=e.Len()
	e.WriteByte('"')
	start:=0
	fori:=0;i<len(s);{
		ifb:=s[i];b<utf8.RuneSelf{
			if0x20<=b&&b!=''&&b!='"'&&b!='<'&&b!='>'&&b!='&'{
				i++
				continue
			}
			ifstart<i{
				e.WriteString(s[start:i])
			}
			switchb{
			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:
				//Thisencodesbytes<0x20exceptfornandr,//aswellas<,>and&.Thelatterareescapedbecausethey
				//canleadtosecurityholeswhenuser-controlledstrings
				//arerenderedintoJSONandservedtosomebrowsers.
				//这种类型打了标志
				e.WriteString(`u00`)
				e.WriteByte(hex[b>>4])
				e.WriteByte(hex[b&0xF])
			}
			i++
			start=i
			continue
		}
		c,size:=utf8.DecodeRuneInString(s[i:])
		ifc==utf8.RuneError&&size==1{
			ifstart<i{
				e.WriteString(s[start:i])
			}
			e.WriteString(`ufffd`)//这种类型打了标志
			i+=size
			start=i
			continue
		}
		//U+2028isLINESEPARATOR.
		//U+2029isPARAGRAPHSEPARATOR.
		//TheyarebothtechnicallyvalidcharactersinJSONstrings,//butdon'tworkinJSONP,whichhastobeevaluatedasJavaScript,//andcanleadtosecurityholesthere.ItisvalidJSONto
		//escapethem,sowedosounconditionally.
		//Seehttp://timelessrepo.com/json-isnt-a-javascript-subsetfordiscussion.
		ifc=='u2028'||c=='u2029'{
			ifstart<i{
				e.WriteString(s[start:i])
			}
			e.WriteString(`u202`)//这种类型打了标志
			e.WriteByte(hex[c&0xF])
			i+=size
			start=i
			continue
		}
		i+=size
	}
	ifstart<len(s){
		e.WriteString(s[start:])
	}
	e.WriteByte('"')
	returne.Len()-len0,nil
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读