unicode编码 utf-8

Golang如何把json中的unicode编码转换成中文字符? - 知乎 https://www.zhihu.com/question/330544039

import (
	"strconv"
	"strings"
)

func UnescapeUnicode(raw []byte) (string, []byte, error) {
	str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(raw)), `\\u`, `\u`, -1))
	if err != nil {
		return "", nil, err
	}
	return str, []byte(str), nil
}

 

import (
	"reflect"
	"testing"
)

func TestUnescapeUnicode(t *testing.T) {
	type args struct {
		raw []byte
	}
	tests := []struct {
		name    string
		args    args
		want    string
		want1   []byte
		wantErr bool
	}{
		// TODO: Add test cases.
		{name: "", args: args{raw: []byte(`{"HelloWorld":"\uB155,\uC138\uC0C1(\u4E16\u4E0A).\u263a"}`)}, want: `{"HelloWorld":"녕,세상(世上).☺"}`, want1: []byte(`{"HelloWorld":"녕,세상(世上).☺"}`), wantErr: false},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, got1, err := UnescapeUnicode(tt.args.raw)
			if (err != nil) != tt.wantErr {
				t.Errorf("UnescapeUnicode() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if got != tt.want {
				t.Errorf("UnescapeUnicode() got = %v, want %v", got, tt.want)
			}
			if !reflect.DeepEqual(got1, tt.want1) {
				t.Errorf("UnescapeUnicode() got1 = %v, want %v", got1, tt.want1)
			}
		})
	}
}

  

 

 

 

 

  

 

posted @ 2022-01-30 17:56  papering  阅读(50)  评论(0编辑  收藏  举报