bandian
V2EX  ›  问与答

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

  •  
  •   bandian · Sep 18, 2020 · 1434 views
    This topic created in 2150 days ago, the information mentioned may be changed or developed.

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

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

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

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

    treblex
        1
    treblex  
       Sep 18, 2020
    编码成 json 呗 json.NewDecoder(resp.Body).Decode(&result)
    caoyouming
        2
    caoyouming  
       Sep 18, 2020
    定义为*json.RawMessage 类型?否则 Data 会被认为是[]byte 类型,在打包时会被打包成 base64 编码的字符串。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2795 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 05:22 · PVG 13:22 · LAX 22:22 · JFK 01:22
    ♥ Do have faith in what you're doing.