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

Golang 中嵌套结构体指针进行 JSON 反序列化的时候有什么好的办法避免空指针

  •  
  •   seth19960929 · 2022-08-31 15:46:18 +08:00 · 521 次点击
    这是一个创建于 611 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如下(由于是使用第三方生成, 一般自己都会定义成结构体, 而不是指针类型)

    type Ad struct {
    	Name   string
    	Banner *Image "json:"banner,omitempty"`
    }
    
    type Banner struct {
    	Url string
    }
    

    反序列化如果没有banner字段, 会给一个空指针, 现在是反序列化之后手动判断然后 new 一个一个赋值. 有没有更好的方法操作?

    dsphper
        1
    dsphper  
       2022-08-31 23:01:10 +08:00
    *Image 改成 Image
    seth19960929
        2
    seth19960929  
    OP
       2022-09-01 09:32:55 +08:00
    @dsphper 第三方生成的, 改不动
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   923 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 18:54 · PVG 02:54 · LAX 11:54 · JFK 14:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.