V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
bandian
V2EX  ›  问与答

golang 如何转换包含 json 字段的结构体为 string

  •  
  •   bandian · 2020-09-18 11:50:05 +08:00 · 934 次点击
    这是一个创建于 1288 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在有一个结构体是这样的:

    type H struct{
    	Id int `json:"id"`
        Data json.RawMessage `json:"data"`
    }
    

    请问如何才能将这个结构体转换为字符串?

    首先 data 是可以包含中文的,所以直接打印 H 可能会无法显示中文,单独把其中的 Data 使用 string(H.Data) 转换的话虽然可用,但是如果字段多的话,这种方式就有点麻烦了。

    treblex
        1
    treblex  
       2020-09-18 12:00:09 +08:00
    编码成 json 呗 json.NewDecoder(resp.Body).Decode(&result)
    caoyouming
        2
    caoyouming  
       2020-09-18 14:58:24 +08:00
    定义为*json.RawMessage 类型?否则 Data 会被认为是[]byte 类型,在打包时会被打包成 base64 编码的字符串。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3251 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:47 · PVG 18:47 · LAX 03:47 · JFK 06:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.