doufan2541 2016-09-17 20:37
浏览 49
已采纳

如何处理具有与json响应不同的json密钥的Struct

I have a struct VideoInfo that has a key in it called embedCode. The API I am querying returns the embed code as embed_code. During unmarshalling the response how do I ensure embed_code goes into embedCode?

Also is there an easy way to take a large json string and automatically turn it into a struct, or can one only use a map?

  • 写回答

2条回答 默认 最新

  • dongshui2254 2016-09-17 21:01
    关注

    With respect to remapping the field names use the corresponding annotation in the structure declaration:

    type VideoInfo struct {
        EmbedCode string `json:"embed_code"`
    }
    

    The marshaller/un-marshaller will only process public field, so you need to capitalise the field name.

    With respect to converting the whole structure, yes it is easy. Declare an instance to un-marshal into and pass a reference to the json.Unmarshal method (from a test):

    data, _ := json.Marshal(request)
    
    var resp response.VideoInfo
    if err := json.Unmarshal(data, &resp); err != nil {
        t.Errorf("unexpected error, %v", err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度