SethShi
0.01D
V2EX  ›  问与答

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

  •  
  •   SethShi · Aug 31, 2022 · 1532 views
    This topic created in 1542 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
    dsphper
    Aug 31, 2022
    1
    *Image 改成 Image
    SethShi
    SethShi
    OP
    Sep 1, 2022
    2
    @dsphper 第三方生成的, 改不动
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4326 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 59ms · UTC 07:53 · PVG 15:53 · LAX 23:53 · JFK 02:53
    ♥ Do have faith in what you're doing.