取消编组时跳过解码Unicode字符串:golang

Ran*_*ngh 1 unicode go

我有这个JSON:

{
    "code":"\u5728\u4e30\u5fb7\u5c14Berro\u8212\u9002\u76841\u623f\u5355\u4f4d"
}
Run Code Online (Sandbox Code Playgroud)

而这个结构

type Text struct {
    Code string
}
Run Code Online (Sandbox Code Playgroud)

如果我使用json.Unmarshal或中的任何一个NewDecoder.Decode,则Unicode会转换为实际的中文。所以,Text.Code

????Berro???1???

我不希望它转换,我想要相同的unicode字符串。

Cra*_*row 5

您可以使用自定义解码器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))
}
Run Code Online (Sandbox Code Playgroud)