V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
SethShi
0.01D
V2EX  ›  问与答

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

  •  
  •   SethShi · Aug 31, 2022 · 1104 views
    This topic created in 1345 days ago, the information mentioned may be changed or developed.

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

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

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

    dsphper
        1
    dsphper  
       Aug 31, 2022
    *Image 改成 Image
    SethShi
        2
    SethShi  
    OP
       Sep 1, 2022
    @dsphper 第三方生成的, 改不动
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   972 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 19:13 · PVG 03:13 · LAX 12:13 · JFK 15:13
    ♥ Do have faith in what you're doing.