取消编组时跳过解码Unicode字符串:golang
问题描述:
I have this JSON:
{
"code":"\u5728\u4e30\u5fb7\u5c14Berro\u8212\u9002\u76841\u623f\u5355\u4f4d"
}
And this struct
type Text struct {
Code string
}
If I use any of the json.Unmarshal
or NewDecoder.Decode
, the Unicode is converted to the actual Chinese. So Text.Code
is
在丰德尔Berro舒适的1房单位
I don't want it to convert, I want the same unicode string.
我有这个JSON: p>
{
“ code “:” \ u5728 \ u4e30 \ u5fb7 \ u5c14Berro \ u8212 \ u9002 \ u76841 \ u623f \ u5355 \ u4f4d“
}
code> pre>
和此结构 p >
type文本结构{
代码字符串
}
code> pre>
如果我使用任何 json。 取消编组 code>或 NewDecoder.Decode code>,Unicode将转换为实际的中文。 因此, Text.Code code>是 p>
在丰德尔Berro舒适的1房单位 code> p>
我不希望它转换,我想要相同的unicode字符串。 p>
div>
答
You can do this with custom decoder https://play.golang.org/p/H-gagzJGPI
package main
import (
"encoding/json"
"fmt"
)
type RawUnicodeString string
func (this *RawUnicodeString) UnmarshalJSON(b []byte) error {
*this = RawUnicodeString(b)
return nil
}
func (this RawUnicodeString) MarshalJSON() ([]byte, error) {
return []byte(this), nil
}
type Message struct {
Code RawUnicodeString
}
func main() {
var r Message
data := `{"code":"\u5728\u4e30\u5fb7\u5c14Berro\u8212\u9002\u76841\u623f\u5355\u4f4d"}`
json.Unmarshal([]byte(data), &r)
fmt.Println(r.Code)
out, _ := json.Marshal(r)
fmt.Println(string(out))
}
答
You could use json.RawMessage
instead of string. https://play.golang.org/p/YcY2KrkaIb
package main
import (
"encoding/json"
"fmt"
)
type Text struct {
Code json.RawMessage
}
func main() {
data := []byte(`{"code":"\u5728\u4e30\u5fb7\u5c14Berro\u8212\u9002\u76841\u623f\u5355\u4f4d"}`)
var message Text
json.Unmarshal(data, &message)
fmt.Println(string(message.Code))
}
答
Simple solution is to escape your backslash by preceding it with another backslash.
func main() {
var jsonRawOriginal json.RawMessage = []byte(`"\u5728\u4e30\u5fb7\u5c14Berro\u8212\u9002\u76841\u623f\u5355\u4f4d"`)
var jsonRawEscaped json.RawMessage = []byte(strings.Replace(string(jsonRawOriginal), `\u`, `\\u`, -1))
fmt.Println(string(jsonRawOriginal)) // "\u5728\u4e30\u5fb7\u5c14Berro\u8212\u9002\u76841\u623f\u5355\u4f4d"
fmt.Println(string(jsonRawEscaped)) // "\\u5728\\u4e30\\u5fb7\\u5c14Berro\\u8212\\u9002\\u76841\\u623f\\u5355\\u4f4d"
var a interface{}
var b interface{}
json.Unmarshal(jsonRawOriginal, &a)
json.Unmarshal(jsonRawEscaped, &b)
fmt.Println(a) // 在丰德尔Berro舒适的1房单位
fmt.Println(b) // \u5728\u4e30\u5fb7\u5c14Berro\u8212\u9002\u76841\u623f\u5355\u4f4d
}