doucuo9126 2016-07-27 19:24
浏览 134
已采纳

取消编组时跳过解码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.

  • 写回答

3条回答 默认 最新

  • dozrhldy285751 2016-07-27 19:43
    关注

    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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成